Question

I intend to use trap to execute some clean up code in case of a failure. I have the following code, but it seems to be have some syntactical issues.

#!/bin/bash

set -e

function handle_error {
    umount /mnt/chroot
    losetup -d $LOOP_DEV1 $LOOP_DEV2
}

trap "{ echo \"$BASH_COMMAND failed with status code $?\"; handle_error; }" ERR

Does any one see an issue with the way the trap has been written. In case of an error the trap does get executed fine but it also throws another unwanted error message below.

/root/myscript.sh: line 60: } ERR with status code 0: command not found
##line 60 is that line of code that exited with a non zero status

How do I write it correctly to avoid the error message? Also what if I had to send arguments $LOOP_DEV1 and $LOOP_DEV2 from the main script to the trap and then to the handle_error function? Right now they are exported as environment variables in the main script. I did some search for trap examples but I couldn't get something similar.

EDIT

I changed the shebang from /bin/sh to /bin/bash. As /bin/sh was already symlinked to bash I did not expect unicorns nor did I see any.

Was it helpful?

Solution

That trap call is creating an interesting recursion, because $BASH_COMMAND (and $?) are being expanded when the trap command executes. However, $BASH_COMMAND at that point is the trap command itself, textually including $BASH_COMMAND (and some quotes and semicolons). Actually figuring out what the command to be executed when the trap fires is an interesting study, but it's not necessary to fix the problem, which you can do like this:

trap '{ echo "$BASH_COMMAND failed with status code $?"; handle_error; }' ERR

Note that replacing " with ' not only avoids immediate parameter expansion, it also avoids have to escape the inner "s.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top