0

Can anyone help? I'm trying to pass a vararray as a parameter to a function. But, I can't make it work. Basically, what I"m trying to do is only to display it's content. But I can't figure out the correct syntaxt.

Anyone can help? I'm using bash GNU bash, version 4.2.46(2)-release (x86_64-redhat-linux-gnu)

-bash-4.2$ vi test.sh
#!/bin/bash

function f(){
  arr=("$0");
  loop
    echo key
    echo value
  end loop;
}


declare -A fooMap=(
  ["key1"]="value1"
  ["key2"]="value2"
)


f fooMap
Cyrus
  • 84,225
  • 14
  • 89
  • 153
amsou
  • 11
  • 7
  • See: [How to pass an associative array as argument to a function in Bash?](https://stackoverflow.com/q/4069188/3776858) – Cyrus Jun 20 '20 at 15:50
  • Hi, I saw that one and I even tried it... #!/bin/bash function iterateMap { local map="${@}" for key in "${!map[@]}" do echo "key - ${key}" echo "value: ${map[$key]}" done } # declare -A fooMap=( ["key1"]="value 1" ["key2"]="value 2" ) iterateMap "$fooMap" BUt I don't get the expected results :( BUt thank you :) – amsou Jun 20 '20 at 16:09
  • @amsou The direct answer is that you can't pass an array (of any sort) as an argument. Arguments are strings -- not objects, data structures, or anything like that. Just strings. Depending on what you're actually trying to accomplish, you could pass the array's *name* (and use various sorts of indirect expansion to get its contents), or you could extract the keys & values from the array and pass those as separate arguments (and then have the function reconstruct the array from its parts), or... well, it really depends on what you're trying to accomplish. – Gordon Davisson Jun 20 '20 at 18:49
  • Hi @GordonDavisson For now, if I can only display the content would be enough. Any idea how to do what you said? – amsou Jun 21 '20 at 06:35

0 Answers0