How to trap exit 1 signal in Shell script?

Kit Ho picture Kit Ho · Feb 26, 2014 · Viewed 10.6k times · Source

I would like to try trapping signal 1 but fail

#!/bin/bash
# capture an interrupt # 0
trap 'echo "Exit 0 signal detected..."' 0
trap 'echo "Exit 1 signal detected..."' SIGHUP

# display something
echo "This is a checkpoint 1"
exit 1

echo "This is checkpoint 2"
# exit shell script with 0 signal
exit 0

Output--
kithokit@15:02:55 trunk (master) $ ./test.sh 
This is a checkpoint 1
Exit 0 signal detected...
kithokit@15:03:44 trunk (master) $ 

Even if it is exit 1, it always trap into trap 0, any one knows how to solve this?

Thanks

Answer

John1024 picture John1024 · Feb 26, 2014

exit 1 does not send a SIGHUP. It exits with return code (AKA exit status) 1. To send a SIGHUP use kill:

#!/bin/bash
# capture an interrupt # 0
trap 'echo "Signal 0 detected..."' 0
trap 'echo "SIGHUP detected..."' SIGHUP

# display something
echo "This is a checkpoint 1"
kill -1 $$

echo "This is checkpoint 2"
# exit shell script with 0 signal
exit 0

$$ is the ID of the current process. So, kill -1 $$ sends signal 1 (SIGHUP) to the current process. The output of the above script is:

This is a checkpoint 1
SIGHUP detected...
This is checkpoint 2
Signal 0 detected...

How to check the return code on exit

If the goal is to check the return code (also known as exit status) rather than to catch special signals, then all we need to do is check the status variable $? on exit:

#!/bin/bash
# capture an interrupt # 0
trap 'echo "EXIT detected with exit status $?"' EXIT

echo "This is checkpoint 1"
# exit shell script with 0 signal
exit "$1"
echo "This is checkpoint 2"

When run at the command line, this produces:

$ status_catcher 5
This is checkpoint 1
EXIT detected with exit status 5
$ status_catcher 208
This is checkpoint 1
EXIT detected with exit status 208

Note that the trap statement can call a bash function which could include arbitrarily complicated statements to process different return codes differently.