Simple example:
user:/$ find /garbage | wc -l
find: '/garbage': No such file or directory
0
user:/$ echo $?
0
find fails, but wc executes and $?=0. I would rather abort, and for $? to be set to find's status code.
This seems to work
user:/$ find /garbage 2> /dev/null && if [ ! $? -eq 0 ]; then exit $?; fi | wc -l
user:/$ echo ?
3
But it's clunky and it feels like there's a cleaner, more bashonic solution.
Taken from man bash:
The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (right‐ most) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.
To set it: set -o pipefail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With