【问题标题】:running basic commands all at once and then sequentially after they all finish一次运行所有基本命令,然后在它们全部完成后依次运行
【发布时间】:2013-03-01 22:39:34
【问题描述】:
我将如何运行如下几个命令,以便在所有后台命令完成后执行(清理)最后一行?
echo "oyoy 1" > file1 &
echo "yoyoyo 2" > file2 &
rm -f file1 file2
当然,回显命令对我来说是不同的,并且需要很长时间才能完成(我可以手动删除文件或使用我知道的另一个脚本,但我想知道如何在一个脚本中完成此操作..)
谢谢!
【问题讨论】:
标签:
linux
bash
parallel-processing
command
【解决方案1】:
来自the docs
wait [n ...]
Wait for each specified process and return its termination sta-
tus. Each n may be a process ID or a job specification; if a
job spec is given, all processes in that job's pipeline are
waited for. If n is not given, all currently active child pro-
cesses are waited for, and the return status is zero. If n
specifies a non-existent process or job, the return status is
127. Otherwise, the return status is the exit status of the
last process or job waited for.
所以你可以像这样等待后台进程完成:
echo "oyoy 1" > file1 &
echo "yoyoyo 2" > file2 &
wait
rm -f file1 file2
【解决方案2】:
或者,如果您有一堆东西正在运行,并且您只需要等待几个进程完成,您可以存储一个 pid 列表,然后只等待那些。
echo "This is going to take forever" > file1 &
mypids=$!
echo "I don't care when this finishes" > tmpfile &
echo "This is going to take forever also" >file2 &
mypids="$mypids $!"
wait $mypids