How do I assign a list to the values of an associative array?

Try this:

declare -A params
params=([n]="200 400 600 800" [p]="0.2 0.4")
declare -p params

Output:

declare -A params='([n]="200 400 600 800" [p]="0.2 0.4" )'

Essentially, you want 2 dimensional array:

1st dimension is de-referenced by 'n' or 'p'.
2nd dimension is de-referenced like a normal array.

bash does not support multi-dimensional arrays.

You are left with these options:

  1. Use combined index as array index in single-dimensional array.

    declare -A params
    params[n,0]=200
    params[n,1]=400 
    params[n,2]=600 
    params[n,3]=800
    params[p,0]=0.2
    params[p,1]=0.4
    
  2. Use 2 level dereferencing:

    declare -A params
    
    #Declare 2 normal arrays.
    array1=(200 400 600 800)
    array2=(0.2 0.4)
    
    #Use the main array to hold the names of these arrays.
    params[n]=array1[@]
    params[p]=array2[@]
    
    #use the array.
    printf "%s\n" "${!params[n]}"
    printf "%s\n" "${!params[p]}"
    
  3. Good old 2 independent arrays:

    param_n=(200 400 600 800)
    param_p=(0.2 0.4)
    

Using these methods, you can iterate through the arrays even when the values contain spaces.


Did you mean to store the lists as elements n and p in an Associative Array? Like this:

#!/bin/bash

declare -A params

params[n]="200 400 600 800"
params[p]="0.2 0.4"

for i in ${!params[@]}; do 
    echo "params[$i] = ${params[$i]}"
done

exit 0

Output

$ bash aalist.sh
params[n] = 200 400 600 800
params[p] = 0.2 0.4

Tags:

Bash