一次运行基本命令,然后在它们全部完成后依次运行

时间:2013-03-01 22:39:35

标签: linux bash parallel-processing command

如何运行以下几个命令,以便在完成所有后台操作后执行最后一行(清理)?

echo "oyoy 1" > file1 &
echo "yoyoyo 2" > file2 &
rm -f file1 file2

当然echo命令对我来说是不同的,需要很长时间才能完成(我可以手动删除文件或使用我知道的其他脚本删除文件,但我想知道如何在一个脚本中完成此操作..)

谢谢!

2 个答案:

答案 0 :(得分:2)

来自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

答案 1 :(得分:0)

或者,如果你有很多东西正在运行,你只需要等待几个过程来完成,你可以存储一个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