Note: ls -d / /nosuch
used as an example below because it fails (exit code 1
) while still producing stdout ( /
) output (in addition to stderr output).
Bash v4.2 + solution:
ccarton , while
, , , , .
Bash v4.2 + , lastpipe
, , ;
ccarton, pipefail
, $?
:
shopt -s lastpipe
shopt -so pipefail
ls -d / /nosuch | while read -r line; do
result=$line
done
echo "result: [$result]; exit code: $?"
( stderr ):
result: [/]; exit code: 1
, $result
, while
, , ls
( ) $?
.
Bash v3 + :
ikkachu , .
:
while read -r line || { ec=$line && break; }; do
result=$line
done < <(ls -d / /nosuch; printf $?)
echo "result: [$result]; exit code: $ec"
$?
, ls
, \n
(printf $?
), read
, ( 1), .
||
( $line
) $ec
.
, \n
, :
while read -r line ||
{ [[ $line =~ ^(.*)/([0-9]+)$ ]] && ec=${BASH_REMATCH[2]} && line=${BASH_REMATCH[1]};
[[ -n $line ]]; }
do
result=$line
done < <(printf 'no trailing newline'; ls /nosuch; printf "/$?")
echo "result: [$result]; exit code: $ec"
( stderr ):
result: [no trailing newline]; exit code: 1