2

In Example_1, when i have declared city to be an array with declare -A, why is Bangalore output first when the array is printed in the for loop?

Bangalore
Remote
Kolkata
Ahmedabad
Hyderabad
Pune
Mumbai
Delhi
Chennai

in Example_2, I believe its sorted in numerical order

example_1

$ cat novice_3.sh 
#!/bin/bash/
declare -A  city=(  ["0"]="Mumbai" ["8"]="Delhi" ["16"]="Kolkata"
                    ["26"]="Bangalore" ["32"]="Chennai"  ["40"]="Pune" 
                    ["50"]="Hyderabad" ["56"]="Ahmedabad"  ["17"]="Remote" )
for i in ${!city[@]};do
echo "${city[$i]}"
done

$ sh novice_3.sh
Bangalore
Remote
Kolkata
Ahmedabad
Hyderabad
Pune
Mumbai
Delhi
Chennai

example_2

$ cat novice_3.sh
#!/bin/bash/
declare   city=( ["0"]="Mumbai" ["8"]="Delhi" ["16"]="Kolkata"
                 ["26"]="Bangalore" ["32"]="Chennai"  ["40"]="Pune" 
                 ["50"]="Hyderabad" ["56"]="Ahmedabad"  ["17"]="Remote" )
for i in ${!city[@]};do
echo "${city[$i]}"
done

$ sh novice_3.sh
Mumbai
Delhi
Kolkata
Remote
Bangalore
Chennai
Pune
Hyderabad
Ahmedabad

1 Answer 1

4

In bash, arrays can be either indexed or associative. Indexed arrays have a numeric index, and are (by default) iterated through by the numeric order of their indices.

An associative array (also known as a hash or hashed array) in bash can use any string as the index (aka key) - this string can be numeric (or appear to be numeric, there's little difference in a bash script), or it can be any other valid string.

Associative arrays in bash are, as they are in many languages, unordered. If you just iterate through the array (e.g. without sorting the keys), you will get the array elements in a semi-random order.

Arrays in bash are, by default, indexed arrays. You can explicitly declare an indexed array with declare -a (with a lowercase a. Whether declared to be indexed, or created as an indexed array by default, if you try to set an array element with a non-numeric index, the index will always evaluate to 0, override or creating the value (if any) of the zeroth element of the array.

e.g.

$ declare -a foo
$ foo[0]=5
$ foo[1]=2
$ declare -p foo
declare -a foo=([0]="5" [1]="2")

OK, that's what you'd expect. But now try setting foo[bar]:

$ foo[bar]=99
$ declare -p foo
declare -a foo=([0]="99" [1]="2")

Similarly, you can declare an array to be associative with declare -A (note the capital A). This will force the array to be associative even if ALL of the indices are numeric.

$ unset foo
$ declare -A foo
$ foo[0]=5
$ foo[1]=2
$ foo[bar]=99
$ declare -p foo
declare -A foo=([bar]="99" [0]="5" [1]="2" )

So, the answer to your question is that in example_1, you declared city to be an associative array. In example_2, you didn't, so it is, by default, an indexed array.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .