olala olala - 4 months ago 7
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

${!mylist[@]}
but I've only seen
${mylist[@]}
before, not
${!mylist[@]}
.

What does the exclamation mark do here?

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

Answer

${!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.

Comments