How do I list subscripts in an array using a bash shell script?



  • Two ways

    Usage is ${!name[*]}

    Usage is ${!name[@]}

    ${!name[*]} - Inside double quotes expands to one word.
    ${!name[@]} - Inside double quotes expands to separate words.

    declare -A MyBucketList
    MyBucketList=([1]="See The Grand Canyon" ["2 or 3"]="Go to Mars" [4]="Climb Mount Everest")
    
    for i in "${!MyBucketList[*]}"
    do
      echo Treat this as one word $i
    done
    
    $ ./associative_array.sh
    Treat this as one word 2 or 3 1 4
    

    Changing the for loop line 4 to:

    for i in "${!MyBucketList[@]}"
    

    then run the script again.

    $ ./associative_array.sh
    Treat this as one word 2 or 3
    Treat this as one word 1
    Treat this as one word 4
    

Log in to reply
 

© Lightnetics 2024