Expanding from this question, we have a use case where we want to pipe the stdout of a command depending on whether that command succeeded or failed.
We start with a basic pipe
command | grep -P "foo"
However we notice that sometimes
command does not output anything to stdout, but does have an exit code of
0. We want to ignore this case and only apply the
grep when the exit code is
For a working example, we could implement a command like this:
OUTPUT=$(command) # exit code is 0 or 1 RESULT=$? if [ $RESULT -eq 0 ]; then return $RESULT; # if the exit code is 0 then we simply pass it forward else grep -P "foo" <<< $OUTPUT; # otherwise check if the stdout contains "foo" fi
but this has a number of disadvantages, namely that you have to write a script, meaning you can't just execute it in the console. It also seems somewhat amateurish.
For a more concise syntax, I'm imagining a fictional ternary operator which pipes if the exit code is
1, otherwise it passes the exit code forwards.
command |?1 grep -P "foo" : $?
Is there a series of operators and utils that will achieve this result?