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?

1
  • 2
    You need to use -A to declare an associative array, not -a. Commented Nov 15, 2014 at 0:21

1 Answer 1

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

2 Comments

@CharlesDuffy Please limit edits to typos, formatting, and other minor tweaks.
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.

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.