Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop through associative array in bash only returns last element

Tags:

arrays

bash

shell

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.

like image 261
mles Avatar asked May 24 '26 03:05

mles


1 Answers

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.