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.
To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command. $ echo $?
Success is traditionally represented with exit 0 ; failure is normally indicated with a non-zero exit-code. This value can indicate different reasons for failure. For example, GNU grep returns 0 on success, 1 if no matches were found, and 2 for other errors (syntax errors, non-existent input files, etc).
Exit code 2 signifies invalid usage of some shell built-in command. Examples of built-in commands include alias, echo, and printf.
Your (probably simplified) example doesn't exhibit the problem you've mentioned:
+ set -eu
+ trap 'echo "E: failed with exitcode $?" 1>&2' ERR
+ true
+ false
++ echo 'E: failed with exitcode 1'
E: failed with exitcode 1
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:
If a sigspec is
ERR
, the command arg is executed whenever a simple command has a non-zero exit status, subject to the following conditions. TheERR
trap is not executed if the failed command is part of the command list immediately following anuntil
orwhile
keyword, part of the test following theif
orelif
reserved words, part of a command executed in a&&
or||
list, or if the command’s return status is being inverted using!
. These are the same conditions obeyed by theerrexit
option.
So if you have, for example, the following:
#! /bin/bash
set -eu
trap 'echo "E: failed with exitcode $?" 1>&2' ERR
false && true
Executed it wouldn't cause the failure to be trapped:
+ set -eu
+ trap 'echo "E: failed with exitcode $?" 1>&2' ERR
+ false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With