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

后端 未结 8 2175
自闭症患者
自闭症患者 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:51

    Here is a solution I came up with today using eval echo ... to do the indirection:

    print_assoc_array() {
        local arr_keys="\${!$1[@]}" # \$ means we only substitute the $1
        local arr_val="\${$1[\"\$k\"]}"
        for k in $(eval echo $arr_keys); do #use eval echo to do the next substitution
            printf "%s: %s\n" "$k" "$(eval echo $arr_val)"
        done
    }
    
    declare -A my_arr
    my_arr[abc]="123"
    my_arr[def]="456"
    print_assoc_array my_arr
    

    Outputs on bash 4.3:

    def: 456
    abc: 123
    

提交回复
热议问题