linux - Linux 超时命令和退出代码

标签 linux bash shell timeout

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

timeout -s SIGTERM 100 command

但我也希望我的 shell 脚本在命令由于某种原因失败时退出。如果命令足够早地失败,则不会达到时间限制,并且超时将以退出代码 0 退出。因此无法使用 trapset -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/

相关文章:

shell - 我可以 ssh 某个地方,运行一些命令,然后给自己一个提示吗?

linux - 管道错误时 CPU 使用率增加

linux - 在 Windows 7 中查看文件权限(如 Linux 操作系统)

linux - 检查脚本中的差异退出状态

Bash 无意中分割命令

linux - 解析json数据时文本编码错误

python - 通过 WMI 脚本关闭 Windows 机器

linux - 用于 Linux 的 OpenGL 3D 网格提取

macos - Mac OS X 10.9 - 设置永久环境变量

linux - Bash脚本以相反的顺序复制编号的文件