1

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!!

9
  • This won't work how you think it will, combo will have one array element that is barworld Commented Apr 17, 2015 at 15:05
  • Exactly, ... can you help to define array, ed loop through it? Commented Apr 17, 2015 at 15:10
  • What exactly is it you are trying to do? Post expected output. Are you trying to make an array inside another ? Commented Apr 17, 2015 at 15:11
  • Yes, ... I need a key, and its value. Is this the correct way to define it? Commented Apr 17, 2015 at 15:13
  • 1
    @JID While you are correct that's only because they didn't declare the array with declare -A. If they did this would do what they expected. So a more constructive version of your comment here (and on the posted answer) would likely have been more useful. Commented Apr 17, 2015 at 15:15

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

4 Comments

Could you also tell me why first element added is the last printed? I got "hello world" and then "foo bar". Is += the wrong way?
Associative arrays don't have an order.
Nice =(. But, ... could you tell me how to iterate the for from the end to the beginning?
There isn't a "beginning" or an "end" to an associative array. Not in the way you mean. Insertion order doesn't matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.