How to pass an associative array as argument to a function in Bash?

后端 未结 8 2144
自闭症患者
自闭症患者 2020-11-27 03:50

How do you pass an associative array as an argument to a function? Is this possible in Bash?

The code below is not working as expected:

function iter         


        
相关标签:
8条回答
  • 2020-11-27 04:53

    From the best Bash guide ever:

    declare -A fullNames
    fullNames=( ["lhunath"]="Maarten Billemont" ["greycat"]="Greg Wooledge" )
    for user in "${!fullNames[@]}"
    do
        echo "User: $user, full name: ${fullNames[$user]}."
    done
    

    I think the issue in your case is that $@ is not an associative array: "@: Expands to all the words of all the positional parameters. If double quoted, it expands to a list of all the positional parameters as individual words."

    0 讨论(0)
  • 2020-11-27 04:55

    Update, to fully answer the question, here is an small section from my library:

    Iterating an associative array by reference

    shopt -s expand_aliases
    alias array.getbyref='e="$( declare -p ${1} )"; eval "declare -A E=${e#*=}"'
    alias array.foreach='array.keys ${1}; for key in "${KEYS[@]}"'
    
    function array.print {
        array.getbyref
        array.foreach
        do
            echo "$key: ${E[$key]}"
        done
    }
    
    function array.keys {
        array.getbyref
        KEYS=(${!E[@]})
    }   
    
    # Example usage:
    declare -A A=([one]=1 [two]=2 [three]=3)
    array.print A
    

    This we a devlopment of my earlier work, which I will leave below.

    @ffeldhaus - nice response, I took it and ran with it:

    t() 
    {
        e="$( declare -p $1 )"
        eval "declare -A E=${e#*=}"
        declare -p E
    }
    
    declare -A A='([a]="1" [b]="2" [c]="3" )'
    echo -n original declaration:; declare -p A
    echo -n running function tst: 
    t A
    
    # Output:
    # original declaration:declare -A A='([a]="1" [b]="2" [c]="3" )'
    # running function tst:declare -A E='([a]="1" [b]="2" [c]="3" )'
    
    0 讨论(0)
提交回复
热议问题