Missing The Last Line in a File

suggest change

Text files are conventionally supposed to end with a newline. If EOF comes before that newline, read can miss the last line. As an example, this file has no newline after three:

$ printf 'one\ntwo\nthree' > file.txt
$ cat file.txt
one
two
three$ while read line; do echo "line $line"; done < file.txt
line one
line two

To make the example above work, continue the loop when the last line is not empty:

$ while read line || [ -n "$line" ] ; do echo "line $line" ; done < file.txt
one
two
three

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents