Search code examples
bashreadlineexit-code

bash read line exits 1


I want to read each lines from an input. Each line is successfully read in a while loop. However the loop ends with the status 1:

$ incr=0
$ while IFS='' read -r line || [[ -n "$line" ]] ; do    
  incr=$((incr+1));    
  echo "$incr: $line"; 
done < <(echo -e "one \ntwo\tthree\nfour")
1: one 
2: two  three
3: four

$ echo "status ${PIPESTATUS[@]}" 
status 1

Why do I get an exit status different than 0?


Solution

  • 1 appears to be the exit status of the command ([[ -n "$line" ]]) that caused the while loop to exit in the first place. It's possible this is a bug in bash, or at least an undocumented difference in which command(s) set $? vs PIPESTATUS.

    You can observe the same difference in a much simpler command:

    $ while false; do echo foo; done
    $ printf '%s\n' "$?" "${PIPESTATUS[@]}"
    0
    1