I was trying to print an index number along with the value of an array. I didn't know how to do it and figured it out via someone else's past post on this site. They basically added a ! in the "for" statement. But I actually don't understand what the "!" is actually doing, please can someone tell me, so I can understand why this works (i.e. prints out the index of $i rather than the value)?

$ cat test6
declare -a car_models
car_models=( honda toyota bmw )

for i in "${!car_models[@]}" ## Meaning of ! in this line plz
echo " $i ${car_models[$i]}" 
$ ./test6
 0 honda
 1 toyota
 2 bmw

1 Answer 1


"${!car_models[@]}" quite literally gives the indexes of the array car_models.

From the manual:

It is possible to obtain the keys (indices) of an array as well as the values. ${!name[@]} and ${!name[*]} expand to the indices assigned in array variable name. The treatment when in double quotes is similar to the expansion of the special parameters @ and * within double quotes.

It works with both indexed and associative arrays:

$ bash -c 'a=([10]=foo bar doo); echo "${!a[@]}"'
10 11 12
$ bash -c 'declare -A aa=([foo]=123 [bar]=456); echo "${!aa[@]}"'
bar foo

You must log in to answer this question.

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