如何在Shell脚本中捕获退出1信号?

时间:2014-02-26 07:07:21

标签: shell signals exit-code bash-trap

我想尝试捕获信号1但是失败

#!/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) $ 

即使它是退出1,它总是陷入陷阱0,任何人都知道如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:4)

exit 1不发送SIGHUP。它以返回码退出(AKA退出状态)1。要发送SIGHUP使用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

$$是当前进程的ID。因此,kill -1 $$将信号1(SIGHUP)发送到当前进程。上述脚本的输出是:

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

如何检查退出时的返回码

如果目标是检查返回代码(也称为退出状态)而不是捕获特殊信号,那么我们需要做的就是在退出时检查状态变量$?

#!/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"

在命令行运行时,会产生:

$ 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

请注意,trap语句可以调用bash函数,该函数可能包含任意复杂的语句,以不同的方式处理不同的返回代码。