
假設我有幾個正在運行的後台任務,但現在我想再運行兩個後台任務,但只等待最後兩個。例如:
# long running commands
sleep 60 &
sleep 60 &
# now wait only for these two:
sleep 5 & sleep 5 & wait; echo waited only for the 5s sleeps.
上面指令的結果是echo指令等待60s。
我知道我可以傳遞 pid 或 jobid 來等待。但由於我是在循環中啟動進程for
,因此我無法輕鬆取得 PID。
我嘗試過這個,但沒有運氣:
{ sleep 3 & sleep 5 & } wait; echo did not wait :
sleep 10 & { sleep 3 ; sleep 3 ; }& wait %2; echo only wait 3s
PS:這個問題是延伸這個更簡單的問題。
答案1
你可以啟動一個子shell:
{ sleep 20 && echo second output ; }
( sleep 2 & wait && echo first output )
子 shell 中的命令wait
僅在那裡有效。
答案2
根據@Kusalananda 在更簡單的問題中的指導,我想出了這個例子。也許不是最簡單的...
下面的所有程式碼都在互動式 shell 中。我只是將其分成幾部分來獲取答案,因為否則很難閱讀。
請注意,在bash
4.1 及更早版本中,!
中的""
, 會觸發互動式 shell 中的歷史記錄替換(這已在版本 4.2 中已修復)。這就是我被欺騙的原因。如果您確實想引用,$!
可以使用"$! "
尾隨空格,以防止歷史記錄替換生效。
unset to_wait;
date;
sleep 3 &
for i in 1 2 3; do
sleep 1 &
# Don't put the ! in "" or you'll get an `event`.
to_wait+=( $! );
done;
wait "${to_wait[@]}";
date;
echo waited 1s for inner processes;
# wait for the rest of the processes (just for illustration)
wait;
date;
echo waited 3s for outer process;