This is basically what I am trying to do: to assign a list to the value of an associative array.
#!/usr/local/bin/bash
declare -A params
params[n]=(200 400 600 800)
params[p]=(0.2 0.4)
But I got this error:
line 4: params[n]: cannot assign list to array member
line 5: params[p]: cannot assign list to array member
Is there any way to get around this problem ?
Normally add a new element in an existing associative array it will get appended at the end of that array. print_r( $arr ); ?> So, a new element can not be added directly at the beginning of an associative array but the existing array can be appended at the end of a new array where the first element is the new element.
Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values. Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.
Shell Scripting: Expert Recipes for Linux, Bash, and More by The associative array is a new feature in bash version 4. Associative arrays link (associate) the value and the index together, so you can associate metadata with the actual data. You can use this to associate a musician with his instrument.
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:
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
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]}"
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.
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" )'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With