Reputation: 85
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.
Upvotes: 1
Views: 1067
Reputation: 99921
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)
Upvotes: 3