bash Shell 脚本在延迟后生成一个进程

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

Shell script spawning a process after a delay

bashshell

提问by gerdemb

How can I spawn a process after a delay in a shell script? I want a command to start 60 seconds after the script starts, but I want to keep running the rest of the script without waiting 60 seconds first. Here's the idea:

如何在 shell 脚本延迟后生成进程?我想要一个命令在脚本启动 60 秒后启动,但我想继续运行脚本的其余部分而不先等待 60 秒。这是想法:

#!/bin/sh
# Echo A 60 seconds later, but without blocking the rest of the script
sleep 60 && echo "A"

echo "B"
echo "C"

The output should be

输出应该是

B
C
... 60 seconds later
A

I need to be able to do this all in one script. Ie. no creating a second script that is called from the first shell script.

我需要能够在一个脚本中完成这一切。IE。没有创建从第一个 shell 脚本调用的第二个脚本。

回答by nos

& starts a background job, so

& 开始后台工作,所以

sleep 60 && echo "A" &

回答by davrieb

A slight expansion on the other answers is to wait for the backgrounded commands at the end of the script.

其他答案的轻微扩展是等待脚本末尾的后台命令。

#!/bin/sh
# Echo A 60 seconds later, but without blocking the rest of the script

set -e

sleep 60 && echo "A" &
pid=$!

echo "B"
echo "C"

wait $pid

回答by lorenzog

Can't try it right now but

现在不能尝试,但是

(sleep 60 && echo "A")&

(sleep 60 && echo "A")&

should do the job

应该做这份工作

回答by Jeroen Vermeulen - MageHost

Alternative:

选择:

echo 'echo "A"' | at now + 1 min

If somehow the OS is not running at the specified time, the command will be executed as soon as it is available.

如果操作系统未在指定时间运行,则该命令将在可用时立即执行。