Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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 ?

like image 420
mynameisJEFF Avatar asked Apr 28 '15 05:04

mynameisJEFF


People also ask

How do you put data in an associative array?

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.

What do associative arrays use for indexes?

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.

What is associative array in shell script?

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.


2 Answers

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.

like image 84
anishsane Avatar answered Sep 28 '22 19:09

anishsane


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" )'
like image 24
Cyrus Avatar answered Sep 28 '22 19:09

Cyrus