我正在使用ksh创建一个脚本,其中执行一个进程(simple_script.sh)并迭代5次。我需要做的是每次执行进程时获取pid并将它们存储在数组中。到目前为止,我可以让脚本执行simple_script.sh 5次,但是无法将pid放入数组中。
while [ "$i" -lt 5 ]
do
./simple_script.sh
pids[$i]=$!
i=$((i+1))
done
正如Andre Gelinas所说,$!
存储了最后一个后台程序的pid。
如果您可以并行执行所有命令,则可以使用此命令
#!/bin/ksh
i=0
while [ "$i" -lt 5 ]
do
{ ls 1>/dev/null 2>&1; } &
pids[$i]=$!
i=$((i+1))
# print the index and the pids collected so far
echo $i
echo "${pids[*]}"
done
结果将如下所示:
1
5534
2
5534 5535
3
5534 5535 5536
4
5534 5535 5536 5537
5
5534 5535 5536 5537 5538
如果要串行执行命令,可以使用wait
。
#!/bin/ksh
i=0
while [ "$i" -lt 5 ]
do
{ ls 1>/dev/null 2>&1; } &
pids[$i]=$!
wait
i=$((i+1))
echo $i
echo "${pids[*]}"
done