Home > database >  How to make exception for a bash script with set -ex
How to make exception for a bash script with set -ex

Time:12-22

I have a bash script that has set -ex, which means the running script will exit once any command in it hits an error.

My use case is that there's a subcommand in this script for which I want to catch its error, instead of making the running script shutdown.

E.g., here's myscript.sh

#!/bin/bash

set -ex

# sudo code here
error = $( some command )
if [[ -n $error ]] ; then
#do something
fi

Any idea how I can achieve this?

CodePudding user response:

You can override the output of a single command

this_will_fail || true

Or for an entire block of code

set  e
this_will_fail
set -e

Beware, however, that if you decide you don't want to use set -e in the script anymore this won't work.

CodePudding user response:

If you want to handle a particular command's error status yourself, you can use as the condition in an if statement:

if ! some command; then
    echo 'An error occurred!' >&2
    # handle error here
fi

Since the command is part of a condition, it won't exit on error. Note that other than the ! (which negates it, so the then clause will run if the command fails rather than it succeeds), you just include the command directly in the if statement (no brackets, parentheses, etc).

BTW, in your pseudocode example, you seem to be treating it as an error if the command produces any output; usually that's not what you want, and I'm assuming you actually want to test the exit status to detect errors.

  •  Tags:  
  • bash
  • Related