2

when i cat this file I get 6 lines (it is a diff file)

bash-3.00$ cat /tmp/voo
18633a18634
> sashabSTP
18634a18636
> sashatSTP
21545a21548
> yheebash-3.00$

however when i read it line by line i only get 5 lines.

bash-3.00$ while read line ; do echo $line ; done < /tmp/voo
18633a18634
> sashaSTP
18634a18636  
> sashatSTP
21545a21548

or this

bash-3.00$ cat /tmp/voo | while read line ; do  echo $line ; done
18633a18634
> sashabSTP
18634a18636
> sashatSTP
21545a21548
bash-3.00$

i am missing the last line 'yhee' from the while loops.

capser
  • 2,442
  • 5
  • 42
  • 74

2 Answers2

5

Note:

21545a21548
> yheebash-3.00$
      ^---- no line break

Your file doesn't terminate with a line break.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • yo got it - the output is cron driven - i guess i will add an echo command to the last line. – capser Dec 03 '13 at 19:15
  • 2
    You can also make the `while` loop run for the unterminated final line by using `while read line || [ -n "$line" ]; do` (see [this previous answer](http://stackoverflow.com/questions/12916352/shell-script-read-missing-last-line/12919766#12919766)). – Gordon Davisson Dec 04 '13 at 17:15
3

If you are wondering why?, this might satisfy your curiosity.

If you work with files which may or may not end up with a new line at end, you can do this:

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

Or this:

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

Read more:

  1. https://stackoverflow.com/a/31397497/3744681
  2. https://stackoverflow.com/a/31398490/3744681
Community
  • 1
  • 1
Jahid
  • 21,542
  • 10
  • 90
  • 108
  • The second option solved a problem for me where the while loop was reading the same line multiple times in a CSV file. Thanks for the tip! – Tom Purl Sep 08 '22 at 20:40