shell read built-in
Yuri Pankov
yuripv at yuripv.net
Mon Oct 22 13:32:08 UTC 2018
Yuri Pankov wrote:
> Eugene Grosbein wrote:
>> Hi!
>>
>> $ echo test | read line; echo $?
>> 0
>> $ echo -n test | read line; echo $?
>> 1
>>
>> Is it right behavior for /bin/sh?
>> This makes it hard for "while read line ... < file"
>> to process last line if it is not followed by new line character.
>
> POSIX defines the exit status for read as (and sh(1) says the same):
>
> The following exit values shall be returned:
> 0 Successful completion.
> >0 End-of-file was detected or an error occurred.
>
> ...and looks like all of /bin/sh, bash, ksh93 seem to agree on the
> behavior here.
BTW, it looks like last line is still parsed despite not having \n, so
you could workaround it using something like (yes, looks ugly):
$ printf "foo bar\n" | (while read a b; do printf "%s %s\n" $a $b; done;
if test -n "$a$b"; then printf "%s %s\n" $a $b; fi)
foo bar
$ printf "foo bar" | (while read a b; do printf "%s %s\n" $a $b; done;
if test -n "$a$b"; then printf "%s %s\n" $a $b; fi)
foo bar
More information about the freebsd-hackers
mailing list