2

I want to pass an array's reference (to/name) from one function to another without it being hidden by a higher-up declaration of the same name.

#!/usr/bin/env bash

f() { local -n a="$1" # The string "array" ("$1") points to the # variable defined in g, but I want it to # point to the variable defined in h. echo "f: ${a[*]}" }

g() { local array=(a b c) # Hides the variable of the same name # defined in h. f "$1" }

h() { local array=(1 2 3) g 'array' }

h

output:

a b c

desired output:

1 2 3

How can I pass the array created in function h via function g to function f BY NAME without it being hidden by the declaration of "array" in function g?


The following is irrelevant to the question.

Explanation, of why I want to do this:

I want to pass collections (strings, arrays, maps (associative arrays)) by name and not by value because my functions take some default parameters the callers don't have to specify in all cases. Example ("collectionType" is a default parameter):

k() {
    local -n collection="$1" # e.g. the name of some array
    local func="$2" # the name of a function to apply to all elements 
    local collectionType="${3:-"$(type_ "$1")}" # type_ returns 
                                                # 'string' 'array' 
                                                # 'map' etc. ...
    # ...
}

Another reason is, that passing (sparse) arrays and associative arrays by value needs one to pass the keys and the length, too.

anick
  • 505
  • 2
  • 13

0 Answers0