I usually use the read command to read an input file to the shell script line by line. An example code such as the one below yields a wrong result if a new line isn't inserted at the end of the last line in the input file, blah.txt.
#!/bin/sh
while read line
do
echo $line
done <blah.txt
So if the input file reads something like -
One
Two
Three
Four
and I do not hit return after Four, the script fails to read the last line, and prints
One
Two
Three
Now if I leave an extra blank line after Four, like,
One
Two
Three
Four
//blank line
the output prints all the lines, including Four. However, this is not the case when I read a line using the cat
command; all lines including the last get printed without me having to add an extra blank line at the end.
Anyone has ideas on why this happens? The scripts I create will mostly be run by others, so it isn't necessary they're going to add an extra blank line at the end of every input file.
I've been trying to figure this out for ages; I'd appreciate it if you have any solutions(of course, the cat
command is one, but I'd like to know the reason behind read not working as well).