1

I have an array made of:

old_array=("color" "red" "shape" "circle" "vote" "10")

(alternating key/values)

I need to build a new_array so that:

echo $new_array[color]
red

echo $new_array[shape]
circle

and so on.

1 Answer 1

3

You need bash's associative arrays.

First, declare the variable as an Associative Array with declare -A:

declare -A new_array

Then set values in the array like you would do with regular arrays:

new_array[color]="red"

You can convert your old_array to new_array like this:

old_array=("color" "red" "shape" "circle" "vote" "10")
declare -A new_array
for (( i = 0; i < ${#old_array[*]}; i += 2 )); do
    key=${old_array[i]}
    value=${old_array[i+1]}
    new_array[$key]=$value
done

You can also write new_array directly:

declare -A new_array=([color]=red [shape]=circle [vote]=10)
Sign up to request clarification or add additional context in comments.

Comments

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.