Home > Mobile >  Bash: Copy an associative array to a normal array
Bash: Copy an associative array to a normal array

Time:02-18

I'm currently learning script programming, and I'm trying to copy an associative array to a normal array. Here's what I got so far:

declare -A array
array[0]=0
array[1]=4
array[2]=4
array[3]=3

copy=${array[@]} 

echo ${copy[0]}
echo ${copy[1]}
echo ${copy[2]}
echo ${copy[3]}

echo ${array[0]}
echo ${array[1]}
echo ${array[2]}
echo ${array[3]}

this method stores all the value into copy[0], which means keys are not copied. Any comments will be appreciated. Thanks!

CodePudding user response:

Maybe this link can help you in this question https://www.shell-tips.com/bash/arrays/

CodePudding user response:

Copy is not an array but var, to make an array use this:

copy=( "${array[@]}" )

But remember that associative array do not preserve order, see this question

  • Related