1

I'm using nested if statements in my shell script. If any statement fails, it has to come out of the script with out executing other sections in the script. I tried using exit 1 and set -e.

I'm not able to use set -e as I have used a few grep statements which would return non zero status.

Could someone please help me How to stop executing a script if any statements fails?

  • Doesn’t exit 1 work? – Jeff Schaller Jul 11 '18 at 18:04
  • I'd recommend fixing the grep's that aren't returning correctly as well. Enabling set -e is a level of conformance that you're demanding of your script, so you're basically working against it rather than using its enforcements. Just my $0.02. – slm Jul 11 '18 at 21:05
  • By "any statements" you seem to mean "almost any statements". – Kusalananda Jul 11 '18 at 21:09
3

You can still use set -e. If you have specific statement which you expect to fail, you simply need to catch the error state and "handle" it:

$ cat 454756.sh
#!/bin/bash
set -e
[[ 1 -eq 2 ]] || :
echo "Still got here!"
$ ./454756.sh
Still got here!

set -e will abort the script on any uncaught error condition. Otherwise you would not be able to use if statements.

# this also still works
set -e
if /bin/false; then
    echo "nope"
else
    echo "yep"
fi

The incantation || : is a succinct way to "eat" any error thrown by any command, which is handy when you're wanting to use set -e and have specific commands whose failure is perfectly okay.

Another way to do this is to unset -e before the command in question, and reset it afterward:

set -e
do_stuff
set +e
/bin/false
set -e
  • 1
    Might worth mentioning true and : are effectively the same and true is a bit more explicit – Sergiy Kolodyazhnyy Jul 11 '18 at 18:18
  • 1
    In bash source they're implemented via same function, and both return exit status of success no matter what, and take arguments without doing anything – Sergiy Kolodyazhnyy Jul 11 '18 at 18:52
  • 1
    Fair enough, I sit corrected. – DopeGhoti Jul 11 '18 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.