Linux Bash 脚本如何在新进程中休眠然后执行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9934828/
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-08-06 05:29:59  来源:igfitidea点击:

Bash script how to sleep in new process then execute a command

linuxbash

提问by David Mulder

So, I was wondering if there was a bash command that lets me fork a process which sleeps for several seconds, then executes a command.

所以,我想知道是否有一个 bash 命令可以让我分叉一个睡眠几秒钟的进程,然后执行一个命令。

Here's an example:

下面是一个例子:

sleep 30 'echo executing...' &

^This doesn't actually work (because the sleep command only takes the time argument), but is there something that could do something like this? So, basically, a sleep command that takes a time argument and something to execute when the interval is completed? I want to be able to fork it into a different process then continue processing the shell script.

^这实际上不起作用(因为 sleep 命令只接受 time 参数),但是有什么可以做这样的事情吗?那么,基本上,一个带有时间参数的 sleep 命令以及在间隔完成时要执行的操作?我希望能够将它分叉到不同的进程中,然后继续处理 shell 脚本。

Also, I know I could write a simple script that does this, but due to some restraints to the situation (I'm actually passing this through a ssh call), I'd rather not do that.

另外,我知道我可以编写一个简单的脚本来执行此操作,但是由于情况的一些限制(我实际上是通过 ssh 调用传递的),我宁愿不这样做。

采纳答案by John Zwinck

You can invoke another shell in the background and make it do what you want:

您可以在后台调用另一个 shell 并使其执行您想要的操作:

bash -c 'sleep 30; do-whatever-else' &

The default interval for sleep is in seconds, so the above would sleep for 30 seconds. You can specify other intervals like: 30mfor 30 minutes, or 1hfor 1 hour, or 3dfor 3 days.

睡眠的默认间隔以秒为单位,因此上面的将睡眠 30 秒。您可以指定其他时间间隔,例如:30m30 分钟、1h1 小时或3d3 天。

回答by Idelic

You can do

你可以做

(sleep 30 && command ...)&

Using &&is safer than ;because it ensures that command ...will run only if the sleep timer expires.

使用&&;它更安全,因为它确保command ...只有在睡眠计时器到期时才会运行。