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

If you’re using Bash 4.3 or newer, the cleanest way is to pass the associative array by name reference 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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)