-1

Cant access hash array value assigned in a for loop outside of it.

declare -A numbers

for((i=0;i<5;i++)){
    randNum=$RANDOM
    numbers[i]=$randNum
    echo ${numbers[i]}
}   
echo ${numbers[0]}

Im able to print the value of the hash array inside the loop. But i expect to do it outside of it.

1 Answers1

1

A few changes to your script will do

#!/bin/bash
declare -a numbers # once numbers everywhere numbers
# Thanks @cyrus for the comment above, well you need an indexed array,
# not an associative one.
for((i=0;i<5;i++))
do # do-done is the preferred syntax
    randNum=${RANDOM} # %RANDOM% is Windows command line stuff 
    # alternatively you could use  a range say ${RANDOM:0:2}
    # for values between 10^0 and 10^2, and so
    echo $randNum
    numbers[i]=$randNum
    echo ${numbers[i]}
done
echo "After loop"
echo ${numbers[0]} # Should work

On {} syntax with the for-loop, read this answer.

sjsam
  • 21,411
  • 5
  • 55
  • 102