I want to have a cleanup action in my Bash scripts, like this:
#! /bin/bash
set -eu
trap 'echo "E: failed with exitcode $?" 1>&2' ERR
true
false
Using $?
came to mind as a natural choice, but this isn't the case. It always contains 0
. Is there any way that I can "spy" on the exitcode in the ERR
trap?
[Update:] I have no idea what I had tested before. This code works like a charm, so I'm leaving it here as a small and good example.
Your (probably simplified) example doesn't exhibit the problem you've mentioned:
Chances are that the command returning
ERR
is executed in a&&
or||
, or subject to other conditions mentioned in the snippet below. Quoting from the manual:So if you have, for example, the following:
Executed it wouldn't cause the failure to be trapped: