How to combine associative arrays in bash? -


does know of elegant way combine 2 associative arrays in bash normal array? here's i'm talking about:

in bash can combine 2 normal arrays follows:

declare -ar array1=( 5 10 15 ) declare -ar array2=( 20 25 30 ) declare -ar array_both=( ${array1[@]} ${array2[@]} )  item in ${array_both[@]};     echo "item: ${item}" done 

i want same thing 2 associative arrays, following code not work:

declare -ar array1=( [5]=true [10]=true [15]=true ) declare -ar array2=( [20]=true [25]=true [30]=true ) declare -ar array_both=( ${array1[@]} ${array2[@]} )  key in ${!array_both[@]};     echo "array_both[${key}]=${array_both[${key}]}" done 

it gives following error:

./associative_arrays.sh: line 3: array_both: true: must use subscript when assigning associative array

the following work-around came with:

declare -ar array1=( [5]=true [10]=true [15]=true ) declare -ar array2=( [20]=true [25]=true [30]=true ) declare -a array_both=()  key in ${!array1[@]};     array_both+=( [${key}]=${array1[${key}]} ) done  key in ${!array2[@]};     array_both+=( [${key}]=${array2[${key}]} ) done  declare -r array_both  key in ${!array_both[@]};     echo "array_both[${key}]=${array_both[${key}]}" done 

but hoping i'm missing grammar allow one-liner assignment shown in non-working example.

thanks!

i don't have one-liner either here different 'workaround' might using string convertion. it's 4 lines, i'm 3 semi-colons answer wanted!

declare -ar array1=( [5]=true [10]=true [15]=true ) declare -ar array2=( [20]=true [25]=true [30]=true )  # convert associative arrays string a1="$(declare -p array1)" a2="$(declare -p array2)"  #combine 2 strings trimming necessary  array_both_string="${a1:0:${#a1}-3} ${a2:21}"  # create new associative array string eval "declare -a array_both="${array_both_string#*=}  # show array definition key in ${!array_both[@]};     echo "array_both[${key}]=${array_both[${key}]}" done 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -