Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In bash, how can cmd1 | cmd2 return cmd1's status code, when cmd1 fails?

Tags:

bash

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.

like image 786
Bean Taxi Avatar asked May 22 '26 19:05

Bean Taxi


1 Answers

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

like image 62
Rany Albeg Wein Avatar answered May 25 '26 18:05

Rany Albeg Wein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!