Nawy Nawy - 7 months ago 25
Bash Question

shell script does not read last line from sysin

I try to get some data from sysin and here is my problem: if data are directed from a file, then the last line is not read.
Example of text file:

line1
line2
line3


My code:

#!/bin/bash
while read line
do
echo "$line"
done


And output:

$ ./test.sh < data.txt
line1
line2


If I write down at the end of my file null string output correct. But I don`t like it.
How to fix this?

Answer

If you need desperately to read files without EOL in the end, then you may check whether returned string is empty or not instead of checking read exit status:

#!/bin/bash
while true; do
  line=''
  read line
  if [ -z "$line" ]; then
    break
  fi
  echo "$line"
done