Issue
I want to pass associate array as a single argument to shell script.
mainshellscript.sh :
#!/bin/bash
declare -A cmdOptions=( [branch]=testing [directory]=someDir [function1key]=function1value [function1key]=function1value )
./anothershellscript.sh cmdOptions
anothershellscript.sh :
#!/bin/bash
#--- first approach, didn't work, shows error "declare: : not found"
#opts=$(declare -p "$1")
#declare -A optsArr=${opts#*=}
#---
# second approach, didnt work, output - declare -A optsArr=([0]="" )
#declare -A newArr="${1#*=}"
#declare -p newArr
#---
I'm suspecting that they way I am collecting array in anothershellscript.sh is wrong, I'm finding a way to access map values simply by providing echo "${optsArr[branch]}"
shall give testing
.
I am using bash version 4.4.23(1)-release (x86_64-pc-msys).
Solution
Passing Associative array to sub script
Associative arrays and regular arrays are not well exported. But you could pass variables by using declare -p
in some wrapper call.
First script:
#!/bin/bash
declare -A cmdOptions=( [branch]=testing [function1key]=function1value
[directory]=someDir [function2key]=function2value )
declare -a someArray=( foo "bar baz" )
declare -x someVariable="Foo bar baz" # Using *export* for simple variables
bash -c "$(declare -p cmdOptions someArray someVariable);. anothershellscript.sh"
Note syntax . anothershellscript.sh
could be replaced by source anothershellscript.sh
.
Doing so, prevent need of temporary files or temporary variable and keep STDIN/STDOUT free.
Then your anothershellscript.sh
could use your variables as is.
#!/bin/bash
declare -p cmdOptions someArray someVariable
could work.
Answered By - F. Hauri Answer Checked By - David Marino (WPSolving Volunteer)