sensorario
sensorario

Reputation: 21620

How to print key and value in an array of array with bash script

I've this script: an array of array, and a loop. Inside the loop, how can I print the key (foo) and the value (bar)???

#!/bin/bash
declare -A combo=()
combo+=(['foo']='bar')
combo+=(['hello']='world')
for window in ${combo[@]};
do
    echo ???
    echo ???
done
exit

expected output:

key: foo   value: bar
key: hello value:world

I'll read this bash manual asap!!

Upvotes: 1

Views: 1957

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80931

Your script is almost correct. As is v.coder's answer.

You need to declare your array as an associative one before you append items to it with string keys.

declare -A combo

Then you need to iterate over the keys of the array (${!combo[@]}") instead of the values (${combo[@]}").

Then the rest of v.coder's answer works just fine.

#!/bin/bash
declare -A combo
combo+=(['foo']='bar')
combo+=(['hello']='world')
for window in "${!combo[@]}"
do
    echo "${window}" # foo
    echo "${combo[${window}]}" # bar
done

Upvotes: 5

Related Questions