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

时间:2022-03-27 01:11:53

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命令允许我为一个休眠了几秒钟的进程提供fork,然后执行一个命令。

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.

^这并不实际工作(因为睡眠命令只花时间参数),但有一些会做这样的事情吗?那么,基本上,一个睡眠命令,当间隔完成时,它需要一个时间参数和一些东西来执行?我希望能够将它分成不同的进程,然后继续处理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调用传递了这个),我宁愿不这样做。

2 个解决方案

#1


11  

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: 30m for 30 minutes, or 1h for 1 hour, or 3d for 3 days.

睡眠的默认间隔是以秒为单位的,所以上面的睡眠时间为30秒。你可以指定其他时间间隔,比如:30分钟30米,1小时1小时,3天3d。

#2


22  

You can do

你可以做

(sleep 30 && command ...)&

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

使用和&比;因为它确保了命令…将只在睡眠计时器过期时运行。

#1


11  

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: 30m for 30 minutes, or 1h for 1 hour, or 3d for 3 days.

睡眠的默认间隔是以秒为单位的,所以上面的睡眠时间为30秒。你可以指定其他时间间隔,比如:30分钟30米,1小时1小时,3天3d。

#2


22  

You can do

你可以做

(sleep 30 && command ...)&

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

使用和&比;因为它确保了命令…将只在睡眠计时器过期时运行。