So I have a script like this:
somecommad | grep --invert-match something
I'd like to be able to conditionally run a different command if somecommand
fails. Here's what I tried:
somecommand | grep --invert-match something || {
echo 'Oops'
}
But that didn't work (the grep
wasn't executed). What is the proper way to do this?
@steeldriver mentioned in the comments that
PIPESTATUS
might work. I tried it, and it worked well. Here's what I did:It runs the command as before, but then I have an
if
statement to look at thePIPESTATUS
array. I only care about the first element, so that is the one I look at. I check it it failed (if the exit code is not0
), and it it did fail, runecho 'Oops'
Another way, depending on the exact behaviour needed, is to use the
pipefail
option:So, if you don't care which of
somecommand
orgrep
failed, as long as one of those did fail: