-1

I am trying to declare an associative array in sh and run through with a for loop:

test_array=([a]=10 [b]=20 [c]=30)

for k in "${!test_array[@]}"
  do
  printf "%s\n" "$k=${test_array[$k]}"
done

And this only returns the last array element:

0=30

Any idea what I am doing wrong?

Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265
  • see e.g. https://stackoverflow.com/a/3113285/297323 – Fredrik Pihl Jul 24 '20 at 08:58
  • Thanks @FredrikPihl, Using the solution proposed by Paused until further notice, I have the same result, only the last array value is shown at key 0. – Milos Cuculovic Jul 24 '20 at 09:00
  • did you declare `test_array` as an associative array? `declare -A test_array` – kvantour Jul 24 '20 at 09:11
  • You mean Posix `sh`? I don't know which program `shell` is. – kvantour Jul 24 '20 at 09:19
  • @kvantour, just tried and is still the same. Note that I'm in sh, not bash. – Milos Cuculovic Jul 24 '20 at 09:24
  • @kvantour, right, sh, sorry, just edited my comment – Milos Cuculovic Jul 24 '20 at 09:24
  • In POSIX sh there are **no** associative arrays. You need to do some really dirty work to mimic these things. Here are some references: [BashFAQ/006](https://mywiki.wooledge.org/BashFAQ/006#Associative_array_hacks_in_older_shells), [Associative arrays in Shell scripts](https://stackoverflow.com/q/688849/8344060), [U&L: Associative Arrays in Shell Scripts](https://unix.stackexchange.com/q/111397/273492) – kvantour Jul 24 '20 at 09:26
  • So, I was just checking the scipt on an Ubuntu 18.04 and it works. The sh I was initially testing on OSx, seems the Mac Shel is somehow different. – Milos Cuculovic Jul 24 '20 at 09:51

2 Answers2

0

I tested this in bash.

Compare these two functions. In the first, I am creating an array with integer indexes, in the second an associative array. I got the expected results in bash. I'm not sure which variant of shell you are using, so I don't know whether you need to add the declaration or quote the array keys or both.

x () 
{ 
    declare -a test_array;
    test_array=([a]=10 [b]=20 [c]=30);
    for k in "${!test_array[@]}";
    do
        printf "%s\n";
        echo "$k=${test_array[$k]}";
    done
}
y

y () 
{ 
    declare -A test_array;
    test_array=(["a"]=10 ["b"]=20 ["c"]=30);
    for k in "${!test_array[@]}";
    do
        printf "%s\n";
        echo "$k=${test_array[$k]}";
    done
}
x
0

Associative arrays are feature of bash 4! It is not available in sh.

As kvantour pointed out in comments, we can mimic the behaviour of associative arrays in sh. See this reference1, reference2.

j23
  • 3,139
  • 1
  • 6
  • 13