Bash Run 命令一段时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16436000/
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
Bash Run command for certain time?
提问by Umair Riaz
I am making a bash script for my use. How can I run a command for certain time, like 20 seconds and terminate command? I tried a lot of solutions but nothing works, I also tried timeout command with no success. Please give me some solution for this.
我正在制作一个 bash 脚本供我使用。如何在特定时间(例如 20 秒)运行命令并终止命令?我尝试了很多解决方案但没有任何效果,我也尝试了 timeout 命令但没有成功。请给我一些解决方案。
For example: I want to run this command in script and terminal after 10 sec
例如:我想在 10 秒后在脚本和终端中运行此命令
some command
回答by Roberto Gomez
Here are some bash scripts and a program called timelimit which may solve your problem. Kill process after it's been allowed to run for some time
这里有一些 bash 脚本和一个名为 timelimit 的程序可以解决您的问题。 在允许运行一段时间后终止进程
EDIT: I think I found a better solution. Try using the timeout program. From the man page: "timeout - run a command with a time limit". For example:
编辑:我想我找到了一个更好的解决方案。尝试使用超时程序。从手册页:“超时 - 运行有时间限制的命令”。例如:
timeout 5s sleep 10s
It basically runs your command and after the specified duration it will kill it.
它基本上运行您的命令,并在指定的持续时间后将其杀死。
回答by mato
On systems that do not provide timeout
command, you can use the following:
在不提供timeout
命令的系统上,您可以使用以下命令:
your-cmd & sleep 30 ; kill $!
That will run potentially long running your-cmd
with timeout of 30 seconds.
这将可能长时间运行your-cmd
,超时为 30 秒。
If your-cmd
does not finish within 30 seconds, it will be sent TERM
signal.
如果your-cmd
在 30 秒内没有完成,将发送TERM
信号。
回答by Matthew Graves
回答by keypress
I suggest 2 options:
我建议2个选项:
- On systems where you have the
timeout
command, you can use it according toman timeout
. - On systems without it (e.g. CentOS 5), you can use the script supplied with bash
/usr/share/doc/bash-3.2/scripts/timeout
. Use it according to its usage information.
- 在您拥有该
timeout
命令的系统上,您可以根据man timeout
. - 在没有它的系统上(例如 CentOS 5),您可以使用随 bash 提供的脚本
/usr/share/doc/bash-3.2/scripts/timeout
。根据其使用信息使用它。
回答by Vladimir Myagdeev
Use sleepand &&operand:
使用sleep和&&操作数:
sleep[time in seconds] && your-command
睡眠[以秒为单位的时间] &&你的命令
Example:
例子:
sleep7 && echo'Hello world!'
sleep7 && echo'Hello world!'