1

I've got a bash script where I need to loop through an array and separately echo the key/value in an array. Seems simple enough but regardless of my combination, I can only get the key to show the numerical key, e.g. 0.

declare -a PROJECT=([Client1]=ProjectClient1 [Client2]=ProjectClient2)
for i in "${!PROJECT[@]}"; do
    echo "1: $i"
    echo "2: ${PROJECT[i]}"
    echo "3: ${PROJECT[$i]}"

None of these result in "Client1". I'm sure it is obvious but what am I missing?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Thomas Bennett
  • 647
  • 6
  • 10

1 Answers1

3

Use

declare -A PROJECT=([Client1]=ProjectClient1 [Client2]=ProjectClient2)

declare -a creates indexed arrays, declare -A creates associative arrays.

In your original code, since the array is indexed, Client1 and Client2 are treated as numeric indexes, using the values of $Client1 and $Client2. Since these variables aren't set, it uses 0 as the default value of both. So it was equivalent to:

declare -a PROJECT=([0]=ProjectClient1 [0]=ProjectClient2)

Since they're both setting element 0, the second one overwrites the first, so it's ultimately equivalent to:

declare -a PROJECT=(ProjectClient2)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • @CharlesDuffy Please limit edits to typos, formatting, and other minor tweaks. – Barmar Nov 15 '14 at 01:04
  • Understood. Would you care to add your own explanation of the _why_ of the behavior with a non-associative array? I think it's an important thing to include, but also don't much care to compete with an answer that is otherwise complete and compelling. On the other hand, if you'd prefer that I add my own answer rather than making substantive additions to yours, I'm happy to do that. – Charles Duffy Nov 15 '14 at 01:05