views:

60

answers:

2

Based on an assoziative array in a bash script I need to iterate over it to get key & value.

#!/bin/bash

declare -A array
array[foo]=bar
array[bar]=foo

I actually don't understand how to get the key while using a for-in loop. Thanks in advance!

+6  A: 

You can access the keys with ${!array[@]}:

bash-4.0$ echo "${!array[@]}"
foo bar

Then, iterating over the key/value pairs is easy:

for i in "${!array[@]}"
do
  echo "key :" $i
  echo "value:" ${array[$i]}
done
tonio
perfect - thanks!
pex
No, that's incorrect. See [my answer](http://stackoverflow.com/questions/3112687/how-to-iterate-over-assoziative-array-in-bash/3113285#3113285).
Dennis Williamson
You are totally right, just corrected the answer. Answered too quickly. Your answer should get the tick mark
tonio
I had the "!" - didn't even notice, there was none, sorry.. :)
pex
+4  A: 

The keys are accessed using an exclamation point: ${!array[@]}, the values are accessed using ${array[@]}.

You can iterate over the key/value pairs like this:

for i in "${!array[@]}"
do
  echo "key  : $i"
  echo "value: ${array[$i]}"
done

Note the use of quotes around the variable in the for statement (plus the use of @ instead of *). This is necessary in case any keys include spaces.

The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.

Dennis Williamson
@John: Bash 4 added associative arrays
Daenyth