Declare dynamic variables in bash functions
The content of this post will be as the title suggests.
My post considers that all variables are not an array.
There are 3 ways
- Use declare with the global flag
-g
. Require bash >= 4.2 or zsh
foo() {
declare -g "my_$1"="my_$2"
}
foo var val
echo $my_var # my_val
Without -g
flag, the final result will be different
foo() {
declare "my_$1"="my_$2"
}
foo var val
echo $my_var # print nothing
- Use
eval
foo() {
eval "my_$1=\"my_$2\""
}
foo var val
echo $my_var # my_val
- Use
printf -v
foo() {
printf -v "my_$1" "%s" "my_$2"
}
foo var val
echo $my_var # my_val
Also, note that function calls should not be wrapped in a command substitution or any similar mechanism which introduces a new subshell. Because subshell inherits all variables from its parents and all modifications stay in the subshell environment. source