4

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

Jolta
  • 2,620
  • 1
  • 29
  • 42
TheOneTeam
  • 25,806
  • 45
  • 116
  • 158

1 Answers1

6

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.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • I see, so is it other way to trap signal 1? something u know many command return signal 1 and i want to trap it – TheOneTeam Feb 26 '14 at 07:23
  • got it . I think i mix up the return code of exit and signal code. they should be two different things. It is clear now. – TheOneTeam Feb 26 '14 at 07:35
  • @KitHo Yes, I see how it looks confusing but they are two different things. Exit status indicates success (code=0) or failure (nonzero code) and sometimes the nonzero code indicates the type of failure. By contrast, signals send any of various messages from one process to another without necessarily causing the other other process to exit. SIGHUP, for example, used to indicate a hangup on the phone line. Now, it often is used to mean "re-read your configuration files." – John1024 Feb 26 '14 at 07:55