Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Bash trap not capture the exit status for an undefined variable?

Tags:

bash

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)

like image 346
pditommaso Avatar asked Jul 03 '18 12:07

pditommaso


People also ask

Does a bash script exit on error?

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.

What does trap do in bash?

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.

How do you exit a bash script?

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”.

What does set Pipefail do?

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.


1 Answers

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.

like image 122
chepner Avatar answered Oct 23 '22 03:10

chepner