bash 如何在 n 秒后退出命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16712031/
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
How to exit from a command after n seconds?
提问by Marcos
I'm writing a script and would like to know how to ask one of the commands to exit after few seconds. For eg. let's suppose my script runs 2 application commands in it.
我正在编写一个脚本,想知道如何要求其中一个命令在几秒钟后退出。例如。假设我的脚本在其中运行 2 个应用程序命令。
#!/bin/bash
for i in `cat servers`
do
<command 1> $i >> Output_file #Consistency command
<command 2> $i >> Output_file #Communication check
done
These commands are to check consistency & communication to/from application. I want to know how do I make sure that command 1 & 2 runs for only few seconds and if there is no response from particular host, move on to next command.
这些命令用于检查与应用程序之间的一致性和通信。我想知道如何确保命令 1 和 2 只运行几秒钟,如果特定主机没有响应,请继续执行下一个命令。
回答by Chris
bashcoreutils has got 'timeout` command.
bashcoreutils 有“超时”命令。
From manual:
从手册:
DESCRIPTION
Start COMMAND, and kill it if still running after NUMBER seconds. SUFFIX may be "s" for seconds (the default), "m" for minutes, "h" for hours or "d" for days.
描述
启动 COMMAND,如果在 NUMBER 秒后仍在运行,则将其杀死。后缀可以是“s”代表秒(默认),“m”代表分钟,“h”代表小时或“d”代表天。
for example:
例如:
timeout 5 sleep 6
timeout 5 sleep 6

