Bash – way to have a function in the bash script auto run on any command error

basherror handlingshellshell-script

I'm writing a shell script that needs to do a bunch of commands and every command depends on every previous command. If any command fails the entire script should fail and I call an exit function. I could check the exit code of each command but I am wondering if there is mode I can enable or a way to get bash to do that automatically.

For example, take these commands:

cd foo || myfunc
rm a || myfunc
cd bar || myfunc
rm b || myfunc

Is there a way where I can somehow signal to the shell before executing these commands that it should call myfunc if any of them fail, so that instead I can write something cleaner like:

cd foo
rm a
cd bar
rm b

Best Answer

You can use bash trap ERR to make your script quit if any command returns status greater than zero and execute your function on exiting.

Something like:

myfunc() {
  echo 'Error raised. Exiting!'
}

trap 'myfunc' ERR

# file does not exist, causing error
ls asd
echo 123

Note that bash trap ERR does implicit set -o errexit or set -e and is not POSIX.

And the ERR trap is not executed if the failed command is part of the command list immediately following until or while keyword, part of the test following the if or elif reserved words, part of a command executed in && or || list, or if the command’s return status is being inverted using !.

Related Question