0

So I have something that looks like this:

a=1
declare -a array
cat ~file | while read line
do
array[$a]=$line
let a=$a+1
echo ${array[(($a - 1))]}
done

read n
m=$n
echo ${array[$m]}

When I echo the array in the loop, it works, but when I try to refer to it outside of the loop, it does not work. Can someone please tell me why? The second echo does not return the value of the array.

user3351901
  • 107
  • 1
  • 3
  • 12

1 Answers1

0

This is because the data is being stored inside a sub-shell, as you do cat ~file | while ....

To prevent it, do: while do ... done < file. Also, note that you can increment with a simple $((a+1)) or even $((a ++)):

a=1
declare -a array
while read line
do
   array[$a]=$line
   $((a+1))
   echo ${array[(($a - 1))]}
done < ~file
fedorqui
  • 275,237
  • 103
  • 548
  • 598