I need to capture error conditions in a Bash script using a trap. For this reason I've both set -e
AND set -u
in my script. However I've noticed that the trap defined in the script is not getting the error status. For example:
set -e
set -u
on_exit() {
exit_status=$?
echo exit_status=$exit_status
exit $exit_status
}
trap on_exit EXIT
X=$Y
The above snippet prints:
line 12: Y: unbound variable
exit_status=0
Whereas I was expecting the error status to be non-zero. After removing set -e
the error status is correctly reported as 1.
What's the reason for that?
Bash version: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)
An exit status code is returned when any Linux command is executed from the terminal, either the command is successful or unsuccessful. This status code can be used to show the error message for unsuccessful execution or perform any particular task by using shell script.
The trap command is frequently used to clean up temporary files if the script exits due to interruption. The following example defines the cleanup function, which prints a message, removes all the files added to the $TRASH variable, and exits the script. $TRASH=$(mktemp -t tmp.
One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.
set -o pipefail causes a pipeline (for example, curl -s https://sipb.mit.edu/ | grep foo ) to produce a failure return code if any command errors. Normally, pipelines only return a failure if the last command errors. In combination with set -e , this will make your script exit if any command in a pipeline errors.
From the change log between 4.0 and 4.1:
x. Fixed a bug that caused $? to not be set correctly when referencing an unset variable with set -u and set -e enabled.
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