对于下面的脚本,bash 数组中的元素列表在循环内按预期打印,但是当在循环外打印相同的元素时,则不是。您能否指出遗漏了什么?
pid_arr=()
pid=10
pid_arr+=($pid)
pid_arr+=(29)
ls -1 | head -2 | while read file
do
ls -1 1>/dev/null 2>/dev/null &
pid=$!
echo "Pid: $pid"
pid_arr+=("${pid}")
echo "Within loop"
echo "${pid_arr[@]}"
done
echo "${pid_arr[@]}"
for pid in "${pid_arr[@]}"
do
echo "Checking pid: $pid"
done
上述脚本的输出
Pid: 10817
Within loop
10 29 10817
Pid: 10818
Within loop
10 29 10817 10818
10 29
Checking pid: 10
Checking pid: 29
期望看到所有 4 个值:10、29、pid1、pid2 但只列出了 10、29,没有列出 pid 值。
根据建议修改了代码(删除了子shell的使用)并按预期工作。
pid_arr=()
pid=10
pid_arr+=($pid)
pid_arr+=(29)
tmp_file=abc-`date +%s`
ls -1 | head -2 > $tmp_file
while read file
do
ls -1 1>/dev/null 2>/dev/null &
pid=$!
echo "Pid: $pid"
pid_arr+=("${pid}")
echo "Within loop"
echo "${pid_arr[@]}"
done < $tmp_file
echo "Outside"
echo "${pid_arr[@]}"
for pid in "${pid_arr[@]}"
do
echo "Checking pid: $pid"
done
rm $tmp_file
输出
Pid: 11122
Within loop
10 29 11122
Pid: 11123
Within loop
10 29 11122 11123
Outside
10 29 11122 11123
Checking pid: 10
Checking pid: 29
Checking pid: 11122
Checking pid: 11123