Can I assign a different exit status to a shell script in a trap handler?
Through trial-and-error, I found that calling exit
in trap
the exit status can be changed. Normal commands, whether fail or succeed, won't change the exit status.
Now I want to know, if I can rely on this behavior, or is it some implementation quirk?
I have been trying to find some doc on this, but to no avail.
Test script:
#!/bin/bash
function handler {
# a successful command won't change script exit status
echo handler, status=$1
# badcommand won't change script exit status
#badcommand
# exit will change script exit status
#exit 23
}
trap 'handler $?' EXIT
#badcommand
Usage:
./trap_test.sh; echo status_out=$?
set -e
in your script, then errors in thetrap
will be returned to the caller. For example, try this command with and without the-e
part:bash -e -c "trap 'false' EXIT"; echo $?