Linux 超时命令和退出代码

The Linux timeout command and exit codes

在 Linux shell 脚本中,如果达到某个时间限制,我想使用 timeout 命令结束另一个命令。总的来说:

timeout -s SIGTERM 100 command

但我还希望我的 shell 脚本在命令因某种原因失败时退出。如果命令足够早地失败,则不会达到时间限制,并且超时将以退出代码 0 退出。因此无法使用 trapset 捕获错误-e,至少我试过了,没用。我怎样才能实现我想做的事情?

您的情况不是很清楚,因为您没有将代码包含在 post 中。

如果在超时值之前完成,

timeout 会以命令的退出代码退出。

例如:

timeout 5 ls -l non_existent_file
# outputs ERROR: ls: cannot access non_existent_file: No such file or directory
echo $?
# outputs 2 (which is the exit code of ls)

来自man timeout

If the command times out, and --preserve-status is not set, then exit with status 124. Otherwise, exit with the status of COMMAND. If no signal is specified, send the TERM signal upon timeout. The TERM signal kills any process that does not block or catch that signal. It may be necessary to use the KILL (9) signal, since this signal cannot be caught, in which case the exit status is 128+9 rather than 124.


参见 BashFAQ105 了解 set -e 的陷阱。