bash Linux 超时命令和退出代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42615374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The Linux timeout command and exit codes
提问by Jadzia
In a Linux shell script I would like to use the timeoutcommand to end another command if some time limit is reached. In general:
在 Linux shell 脚本中,如果达到某个时间限制,我想使用timeout命令来结束另一个命令。一般来说:
timeout -s SIGTERM 100 command
But I also want that my shell script exits when the command is failing for some reason. If the command is failing early enough, the time limit will not be reached, and timeout will exit with exit code 0. Thus the error cannot be trapped with trapor set -e, as least I have tried it and it did not work. How can I achieve what I want to do?
但我也希望我的 shell 脚本在命令由于某种原因失败时退出。如果命令失败得足够早,则不会达到时间限制,超时将以退出代码 0 退出。因此,无法使用trap或set -e捕获错误,至少我已经尝试过了,但没有奏效。我怎样才能实现我想做的事?
回答by codeforester
Your situation isn't very clear because you haven't included your code in the post.
你的情况不是很清楚,因为你没有在帖子中包含你的代码。
timeout
does exit with the exit code of the command if it finishes before the timeout value.
timeout
如果它在超时值之前完成,则使用命令的退出代码退出。
For example:
例如:
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)
From man timeout
:
来自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.
如果命令超时,并且未设置 --preserve-status,则以状态 124 退出。否则,以 COMMAND 状态退出。如果未指定信号,则在超时时发送 TERM 信号。TERM 信号会杀死任何不阻塞或捕获该信号的进程。可能需要使用 KILL (9) 信号,因为无法捕捉到该信号,在这种情况下,退出状态为 128+9 而不是 124。
See BashFAQ105to understand the pitfalls of set -e
.
请参阅BashFAQ105以了解set -e
.