0

At this link, the author discusses looping to read files from a list.

#!/bin/bash
while IFS= read -r file
do
  [ -f "$file" ] && rm -f "$file"
done < "/tmp/data.txt"

The problem is, the source file seems to require a newline following the last line it reads.

/tmp/data.txt
file1.txt
file2.txt
file3.txt // <- if there is no newline, this file will not be read

If no newline exists after the last file, it will not be read.

/tmp/data.txt
file1.txt
file2.txt
file3.txt
// <- this newline, now makes file3.txt able to be read

Is there a way to cleanly rewrite the code to pick up the last line file3.txt regardless of whether or not a newline follows it?

Edit:

The answer pointed to in the comment solves the problem. Added || [ -n "$file" ]; to the while statement. The code is as follows.

#!/bin/bash
while IFS= read -r file || [ -n "$file" ];
do
  [ -f "$file" ] && rm -f "$file"
done < "/tmp/data.txt"
Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207

0 Answers0