shell - 如何在 Shell 脚本中捕获 exit 1 信号?

标签 shell signals exit-code bash-trap

我想 try catch 信号 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) $ 

即使是exit 1,也总是陷入trap 0,谁知道怎么解决?

谢谢

最佳答案

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 函数,该函数可以包含任意复杂的语句以不同方式处理不同的返回码。

关于shell - 如何在 Shell 脚本中捕获 exit 1 信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22034206/

相关文章:

qt - 在Qt中退出应用程序

Bash shell 脚本从文件名中查找丢失的文件

arrays - 重置数组并用 bash 脚本中的值填充它

shell - 使用 Set -e ,如何为一个命令设置异常

php - 在 CakePHP shell 中搜索

c - 如何不断地从父进程向子进程发送信号?

python - PyErr_CheckSignals 没有接收到信号

bash - diff 的错误退出值是多少?

c - 信号处理程序不处理信号

c# - CruiseControl.NET (CCNET) "Process exited event received"但构建等待?