arraysbashloopsshell

Bash array value different inside while loop


I have a pretty simple shell script that uses a while loop to read values from a file, place them into an array and then print the content of the array. It correctly displays the content of the array after each addition inside the while loop. The issue is when I view the content of the array outside of the loop the table appears to be empty.

Here is the content of the script:

ctr=0
arr=()
cat "alpha.txt" |\
while IFS="," read data
do
   arr+=("$data")
   echo "$ctr.data: $data"
   echo "array inside loop: ${arr[@]}"
   let "ctr=ctr+1"
done
echo
echo "+++++"
echo "array outside loop: ${arr[@]}"
echo
echo "${arr[1]}"
echo "${arr[2]}"

The content of alpha.txt:

aaa
bbb
ccc

The output from the program:

0.data: aaa
array inside loop: aaa
1.data: bbb
array inside loop: aaa bbb
2.data: ccc
array inside loop: aaa bbb ccc

+++++
array outside loop: 

I can't understand why I can't display the array's content outside of the loop. Any advice would be appreciated.


Solution

  • the following is the solution:

    ctr=0
    arr=()
    while IFS="," read data
    do
       arr+=("$data")
       echo "$ctr.data: $data"
       echo "array inside loop: ${arr[@]}"
       let "ctr=ctr+1"
    done < "alpha.txt"
    echo
    echo "+++++"
    echo "array outside loop: ${arr[@]}"
    echo
    echo "${arr[1]}"
    echo "${arr[2]}"
    

    and why that is the solution:

    because of pipelines making subshells, which means variables made in pipelines will not be seen by the script