shellfileeof

Last line of a file is not reading in shell script


I have a text file foo.txt with the below text as content,

1
2
3
4
5

I have a shell script,

file="foo.txt" 
while IFS= read -r line
do
   echo "$line"
done < "$file"

But this prints only till 4.


Actual Output:

1
2
3
4

How to get the expected output as below?

Expected Output:

1
2
3
4
5

Solution

  • This is due to missing line break in the last line of your input file.

    You can use this loop to read everything:

    while IFS= read -r line || [ -n "$line" ]; do
        echo "$line"
    done < "$file"
    

    For the last line without line break, read doesn't return a success hence [ -n "$line" ] check is done to make sure to print it when $line is not empty.

    PS: If you don't mind changing your input file then use printf to append a newline using:

    printf '\n' >> "$file"
    

    And then read normally:

    while IFS= read -r line; do
        echo "$line"
    done < "$file"