In bash, how can cmd1 | cmd2 return cmd1's status code, when cmd1 fails? -
simple example:
user:/$ find /garbage | wc -l find: '/garbage': no such file or directory 0 user:/$ echo $? 0
find
fails, wc
executes , $?=0
. rather abort, , $?
set find
's status code.
this seems work
user:/$ find /garbage 2> /dev/null && if [ ! $? -eq 0 ]; exit $?; fi | wc -l user:/$ echo ? 3
but it's clunky , feels there's cleaner, more bashonic solution.
taken man bash
:
the return status of pipeline exit status of last command, unless pipefail option enabled. if pipefail enabled, pipeline's return status value of last (right‐ most) command exit non-zero status, or 0 if commands exit successfully. if reserved word ! precedes pipeline, exit status of pipeline logical negation of exit status described above. shell waits commands in pipeline terminate before returning value.
to set it: set -o pipefail
Comments
Post a Comment