I would like to do equivalent of name referencing from a function run in a subshell, so that arbitrary variable (e.g. associative array) is then available in the parent.
Note on duplicates: I found similar asked 12 years ago (and others referenced within), but the question was fairly limited to a simple variable and fixed variable name - I would like arbitrary and multiple ones, possibly with complex values. Also, the answers are not that applicable focusing on solving the problem differently. I have the subshell function running remotely, so I cannot use those, e.g. I cannot use writing to local files, reverse order piping, etc. Also, I am fine if the solution is Bash-specific.
If it were to be done within the same shell environment, the example would be:
#!/bin/bash func() { declare -n var="$1" var["a"]="word1" var["b"]="word2" } declare -A x=() func x for e in "${!x[@]}"; do printf "[%s]=%s\n" "$e" "${x[$e]}" ; done This works just fine:
[b]=word2 [a]=word1 Now, of course, once func x is to be executed in a subshell, all is lost.
Instead, I am attempting to serialize the variable with declare -p:
func2() { declare -A X=() X["p"]="word3" declare -p X } This works with a subshell as I can eval the output, although not sure how safe this approach is:
eval "$( func2 )" The raw output of func2() is:
declare -A X=([p]="word3" ) Now within the parent, I have associative array X available.
However, how do I do this with:
- arbitrary variable name(s) that I can pass into the function;
- safely, possibly with
printf "%q"?
Running a regex with respect to (1) feels rather hackish and I can't get (2) to work at all.
func()locally but executing it remotely on another machine using something likessh user@host "bash -c '$(typeset -f func); func x'"or that you're usingsshto call your whole shell script remotely or something else?-fis something I started doing recently and it's neat, but (I believe) the two make no difference when it comes to returning values - the problem is the same.the_script) is on a remote machine, are you trying to return the values fromfunc()to the code that calls it within that same script on the remote machine or to the script that calledssh user@host the_scripton the local machine?declare -n. Sometimes I use the function in both scenarios, but the latter requires me to address it as per the question. Typically, it's one and the same script local (caller) and remote (callee). The script either runs fully local or gets (only some) values from remote. So I end up having a function that collects data wherever it is executed, but should reliably return it to the caller.