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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:40:50  来源:igfitidea点击:

Bash Run command for certain time?

bashtimeoutcommand

提问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 timeoutcommand, you can use the following:

在不提供timeout命令的系统上,您可以使用以下命令:

your-cmd & sleep 30 ; kill $!

That will run potentially long running your-cmdwith timeout of 30 seconds.

这将可能长时间运行your-cmd,超时为 30 秒。

If your-cmddoes not finish within 30 seconds, it will be sent TERMsignal.

如果your-cmd在 30 秒内没有完成,将发送TERM信号。

回答by Matthew Graves

Are you looking to schedule the execution of the script? Then cronis your friend.

您是否要安排脚本的执行?那么cron就是你的朋友。

回答by keypress

I suggest 2 options:

我建议2个选项:

  • On systems where you have the timeoutcommand, you can use it according to man 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!'