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:
Note that bash trap
ERR
does implicitset -o errexit
orset -e
and is not POSIX.And the
ERR
trap is not executed if the failed command is part of the command list immediately followinguntil
orwhile
keyword, part of the test following theif
orelif
reserved words, part of a command executed in&&
or||
list, or if the command’s return status is being inverted using!
.