Home > Mobile >  How bash code try to read file without newline?
How bash code try to read file without newline?

Time:02-18

while read -r p1 p2 || [ -n "$p1" ]; do
  printf '%s %s\n' "$p1 $p2"
  scTeam =($p1)
  bcTeam =($p2)
done < $1

enter image description here

The problem is that the do-while loop will miss the last line/variable in my .dat files if I don't add "|| [ -n $p1]" in the condition statement. I thought the problem is coming from the newline problem. It's strange. Could anyone explain more about this problem. Thanks a lot lot lot!!

CodePudding user response:

Reason: the read command fails when the input is not terminated with a newline.

See this Reference for detailed explanation.

In the reference, you can see

According to the POSIX spec for the read command, it should return a nonzero status if "End-of-file was detected or an error occurred." Since EOF is detected as it reads the last "line", it sets $line and then returns an error status, and the error status prevents the loop from executing on that last "line". The solution is easy: make the loop execute if the read command succeeds OR if anything was read into $line.

CodePudding user response:

If your bash supports process substitution, you could do a

done <(cat $1; echo)

which would enforce a trailing newline. If the file already has a newline at the end, you would get one additional, empty line, but your loop can handle empty lines, so this should not be a problem.

  • Related