等待退出所有子进程退出

时间:2011-09-08 04:14:15

标签: bash shell wait

在我的shell脚本中,'wait'不等待xx.sh,yy.sh和zz.sh退出!为什么!

#main.sh
#!/bin/bash
idx=0
while (($idx<1))
do`cd ff
    ./xx.sh >xx&
    ./yy.sh >yy&
    ./zz.sh >zz&
    cd -
    idx=$(($idx+1))  
done|ls
wait
echo "END"


#xx.sh,yy.sh,zz.sh is for sleep

2 个答案:

答案 0 :(得分:2)

命令在不同的子shell中运行,因此等待不会等待正确的进程。要查看此内容,请尝试

./xx.sh >xx &
./yy.sh >yy &
./zz.sh >zz &
wait #this should wait for all of the processes

如果要使用循环生成,则构建要运行的命令字符串,然后在主脚本中运行它(不在for循环中)。

答案 1 :(得分:0)

#main.sh
#!/bin/bash
idx=0

( # subshell
   while (($idx<1))
   do
       echo ./xx.sh \>xx&
       echo ./yy.sh \>yy&
       echo ./zz.sh \>zz&
       sleep 5;
       echo "all done";
       idx=$(($idx+1))
    done
)& FOR=$!

echo "Waiting for process $FOR"
wait $FOR
echo "END"