2 ms·
I was looking more into this and found something interesting[0]: > A variable can be assigned the nameref attribute using the -n option to the declare or local
by noisy_boy 5y ago
I was looking more into this and found something interesting[0]:
> A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see Bash Builtins) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable’s value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to the function.
So something like below:
set_var() {
local -n vname=$1 # use nameref for indirection
# some processing and assign value
vname="abcd"
}
use_var() {
local output
set_var output # call function to populate the variable
echo "output=$output"
unset -n output
}
use_var
I guess this is pretty close to "clean". Unfortunately, it is only available in bash 4.3, if I'm not wrong, so I don't have a choice to use it (our hosts use 4.2.x).
[0]: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html https://www.gnu.org/software/bash/manual/html_node/Shell-Par...