olala olala - 2 months ago 5x
Bash Question

what does the ! mean in this expression: ${!mylist[@]}

I'm trying to understand a shell script written by a previous group member. there is this for loop. I can understand it's looping through a list

but I've only seen
before, not

What does the exclamation mark do here?

for i in ${!mylist[@]};
echo ${mylist[i]}


${!mylist[@]} returns the keys to an an array. This differs from ${mylist[@]} which returns the values in the array.

As an example, let's consider this array:

$ arr=(abc def ghi)

In order to get its keys:

$ echo "${!arr[@]}"
0 1 2

In order to get its values:

$ echo "${arr[@]}"
abc def ghi

From man bash:

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.