Reputation: 19551
I have put
set -e
set -u
at the top of my BASH script to make it fail as opposed to going on.
Is there a way for me to specify some code to be run on failure?
If there's no better way, I can make my program a
three files:
a
.a
.a_onfail
and have a
just be
# headers etc
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
$(DIR)/.a || $(DIR)/.a_onfail
Upvotes: 1
Views: 161
Reputation: 4817
It seems that trap '...' ERR
does not work with unset variables.
You can use a subshell instead of two separate script files:
#!/bin/sh -eu
main() {
echo "$X"
}
on_failure() {
echo "Failure"
}
(main) || on_failure
Upvotes: 2
Reputation: 11425
You could try solve this using trap. Eg: trap "ERROR=1" ERR
and trap '[ "$ERROR" = "1" ] && on_error' EXIT
and then provide a on_error
function.
Upvotes: 1
Reputation: 339786
Did you try:
trap ... ERR
If a sigspec is ERR, the command arg is executed whenever a simple command has a non-zero exit status,
Upvotes: 2