How to use `while read` (Bash) to read the last line in a file if there’s no newline at the end of the file?
I use the following construct:
while IFS= read -r LINE || [[ -n "$LINE" ]]; do echo "$LINE"done
It works with pretty much anything except null characters in the input:
- Files that start or end with blank lines
- Lines that start or end with whitespace
- Files that don't have a terminating newline
Using grep
with while loop:
while IFS= read -r line; do echo "$line"done < <(grep "" file)
Using grep .
instead of grep ""
will skip the empty lines.
Note:
Using
IFS=
keeps any line indentation intact.File without a newline at the end isn't a standard unix text file.