For the below script, list of elements in bash array is printed as expected within the loop, but when the same is printed outside the loop, its not. Can you please provide pointers on what is being missed?
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
Output for the above script
Pid: 10817
Within loop
10 29 10817
Pid: 10818
Within loop
10 29 10817 10818
10 29
Checking pid: 10
Checking pid: 29
Was expecting to see all the 4 values : 10, 29, pid1, pid2 But only 10, 29 are listed and not the pid values.