Sunday, May 5, 2024
13
rated 0 times [  13] [ 0]  / answers: 1 / hits: 6233  / 2 Years ago, sun, april 3, 2022, 5:43:03

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?


More From » command-line

 Answers
6

@steeldriver mentioned in the comments that PIPESTATUS might work. I tried it, and it worked well. Here's what I did:


somecommand | grep --invert-match something
if [ "${PIPESTATUS[0]}" != "0" ]; then
echo 'Oops'
fi

It runs the command as before, but then I have an if statement to look at the PIPESTATUS 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 not 0), and it it did fail, run echo 'Oops'


[#1087] Sunday, April 3, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ranquctive

Total Points: 391
Total Questions: 103
Total Answers: 104

Location: South Sudan
Member since Thu, Feb 4, 2021
3 Years ago
ranquctive questions
;