Trailing newlines and the bash 'read' builtin Trailing newlines and the bash 'read' builtin shell shell

Trailing newlines and the bash 'read' builtin


If you want the above loop to process the incomplete line, do this:

echo -n $'a\nb\nc' | while read x || [[ $x ]]; do echo = $x =; done

which gives:

= a == b == c =

When read encounters the incomplete line, it does read that into the variable (x in this case) but returns a non-zero exit code which would end the loop, and || [[ $x ]] takes care of running the loop for the incomplete line as well. When read is called the next time, there is nothing to read and it exits with 1, setting x to an empty string as well, which ensures that we end the loop.


Related


$ man bash   read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]          One line is read from the standard input, ...

I think the key is: How to define "One line".
Does text without a '\n' at the end makes One line?
I guess read don't think so.