Sample Header Ad - 728x90

Bash pass an associative array to/from a background function

2 votes
2 answers
1361 views
I am trying to pass a bash associative array by reference into a function and then be able to see the changed content back in the main script after the function is complete. I have found what seems to be the most straightforward way to do it [here](https://unix.stackexchange.com/a/462089/21348) except in my case the function is being run ***in the background***. It seems that no matter what I do, I can't get the linked solution above to work in this scenario. In the snippet below, I've taken the working example code from the link above and simply added a "&" to the function call and a "wait" on the following line to demonstrate the issue as simply as possible. I suspect bash is trying to prevent the main script and the background function from stepping on each other, but I don't know how to solve it. **Example Code:** foo () { declare -n fooarray="$1" fooarray["fookey"]=foovalue } declare -A myarray myarray["mainkey"]=mainvalue foo myarray & wait for key in "${!myarray[@]}"; do printf '%s = %s\n' "$key" "${myarray[$key]}" done **Output:** bash-4.4$ ./test.sh mainkey = mainvalue Any help would be appreciated. I know I could potentially do silly things like writing the contents of the array out to a file and then parsing it back in, but I'm hoping there's a more elegant solution than that.
Asked by demarcmj (231 rep)
Feb 24, 2022, 09:16 PM
Last activity: Jul 30, 2023, 04:32 PM