3

This should print the whole associative array to the console:

#!/bin/sh

declare -a array=([key1]='value1' [key2]='value2')

for key in ${!array[@]}; do
    echo "Key = $key"
    echo "Value = ${array[$key]}"
done

echo ${array[key1]}
echo ${array[key2]}

Instead it prints oly the last variable:

[mles@sagnix etl-i_test]$ ./test.sh 
Key = 0
Value = value2
value2
value2

Where is my fault?

@htor: Bash Version is 3.2.25(1)-release.

4
  • Take a look at stackoverflow.com/q/688849/1983854 , there are many solutions to this. Commented May 22, 2013 at 9:49
  • 2
    are you sure /bin/sh is actually /bin/bash? also associative arrays are built using -A not -a ... see answer below Commented May 22, 2013 at 9:51
  • /bin/sh is a symbolic link to bash on my system Commented May 22, 2013 at 12:26
  • What's your BASH version? Provide the output of echo $BASH_VERSION in your question. Commented May 22, 2013 at 12:58

2 Answers 2

6

Associative arrays are supported in Bash 4 and newer versions. An array declared with the -a option is just a regular array that can be indexed by integers, not keys. This declaration results in the array with one element value2. When iterating over the keys with for key in ${!array[@]} the value of $key is 0 and therefore you get the first element.

Given the error output you get when trying to use -A to declare to array, I assume your Bash version is older than 4. Inspect the variable $BASH_VERSION.

For a deeper explaination of arrays, see http://mywiki.wooledge.org/BashGuide/Arrays.

Sign up to request clarification or add additional context in comments.

Comments

3
#!/bin/bash

declare -A array=([key1]='value1' [key2]='value2')

for key in ${!array[@]}; do
    echo "array[$key] = ${array[$key]}"
done

echo ${array[key1]}
echo ${array[key2]}

2 Comments

that gives me an error ./test.sh: line 3: declare: -A: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...]
@mles: you aren't using bash 4 or later.

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.