在 Linux shell 脚本中,如果达到某个时间限制,我想使用 timeout 命令结束另一个命令。一般而言:
timeout -s SIGTERM 100 command
但我也希望我的 shell 脚本在命令由于某种原因失败时退出。如果命令足够早地失败,则不会达到时间限制,并且超时将以退出代码 0 退出。因此无法使用 trap 或 set -e 捕获错误>,至少我已经尝试过了,但没有用。我怎样才能实现我想做的事情?
最佳答案
你的情况不是很清楚,因为你没有在帖子中包含你的代码。
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
的陷阱。
关于linux - Linux 超时命令和退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42615374/