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

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

    If you're using Bash 4.3 or newer, the cleanest way is to pass the associative array by name and then access it inside your function using a name reference with local -n. For example:

    function foo {
        local -n data_ref=$1
        echo ${data_ref[a]} ${data_ref[b]}
    }
    
    declare -A data
    data[a]="Fred Flintstone"
    data[b]="Barney Rubble"
    foo data
    

    You don't have to use the _ref suffix; that's just what I picked here. You can call the reference anything you want so long as it's different from the original variable name (otherwise youll get a "circular name reference" error).

提交回复
热议问题