PIDS+=$!
…不是你想的那样。考虑:
PIDS=( )
PIDS+=11
PIDS+=22
PIDS+=33
declare -p PIDS
…如果你
期待
declare -a PIDS='([0]="11" [1]="22" [2]="33")
……你会错的,因为
发射是:
declare -a PIDS='([0]="112233")'
+=
只有当右边的东西是数组时,才追加一个新的数组元素。
因此,你得到一个
not a child of this shell
错误,因为将所有PID连接到一个字符串中的结果并不是一个实际存在的PID。
PIDS+=( "$!" )
提供端到端示例:
#!/usr/bin/env bash
# run four different processes; two exit status 0, one exits status 1, on exits status 2
# ...exits happen at delays ranging between 2-5 seconds.
delays=( 5 3 2 4 )
exits=( 0 0 1 2 )
for idx in "${!delays[@]}"; do
(sleep "${delays[$idx]}"; exit "${exits[$idx]}") &
pids+=( "$!" )
done
exit_status=0
for pid in "${pids[@]}"; do
wait "$pid"; (( exit_status |= $? ))
done
echo "Combined exit status is $exit_status"
exit "$exit_status"
Combined exit status is 3