Aaron Yodaiken
Aaron Yodaiken

Reputation: 19551

run code on failure

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

Answers (3)

Mark Edgar
Mark Edgar

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

Mattias Wadman
Mattias Wadman

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

Alnitak
Alnitak

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

Related Questions