2

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

I declare my hash array:

declare -A some_array

And I declare my function:

some_function() {
  ..
}

How can I send the array as an argument to the function in order to access it?

I know that I can use it as a global variable, but it's not the way out when I have a lot of hash arrays I want to use with some function.

If there is no way to do it, how can I assign to the one hash array value of other?

Community
  • 1
  • 1

1 Answers1

2

Access it as a global variable (simply refer to it by name inside your function). There is no array passing in Bash. There are awkward techniques that try to do this, but I recommend avoiding the mess.

Other options include writing your entire script in a language such as Python or Perl which supports passing arrays, hashes or their references.

In Bash 4.3 or later you can use name references, but there are caveats.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • This doesn't seem to work. The changes may be visible within the function, but are lost outside of it. – user1167662 Jun 06 '19 at 19:32
  • @user1167662: Did you declare the array inside the function? That makes it local to the function. If you declare it outside then it's global. – Dennis Williamson Jun 06 '19 at 19:34
  • I tried inside and outside a function. I also tried `declare -gA var_name`, which I understand is supposed to make the variable have global scope, but that didn't do the trick either. – user1167662 Jun 08 '19 at 01:56
  • @user1167662: This snippet works as advertised: `declare -A arr; my_func () { arr['customer']=$1; }; my_func Bob; printf '%s\n' "${arr['customer']}"; declare -p arr`. Does that work for you? What version of Bash? If that doesn't work or doesn't provide clues as to what to look for in your code, then I recommend that you ask a new question and show the code you tried and what the result is and what the expected result is. – Dennis Williamson Jun 08 '19 at 03:00