creating environment variable with user-defined name - indirect variable expansion

核能气质少年 提交于 2019-11-29 16:49:20

To get closure: the OP's question boils down to this:

How can I get the value of a variable whose name is stored in another variable in bash?

var='value'    # the target variable
varName='var'  # the variable storing $var's *name*

gniourf_gniourf provided the solution in a comment:

Use bash's indirection expansion feature:

echo "${!varName}"  # -> 'value'

The ! preceding varName tells bash not to return the value of $varName, but the value of the variable whose name is the value of $varName.
The enclosing curly braces ({ and }) are required, unlike with direct variable references (typically).
See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

The page above also describes the forms ${!prefix@} and ${!prefix*}, which return a list of variable names that start with prefix.


bash 4.3+ supports a more flexible mechanism: namerefs, via declare -n or, inside functions, local -n:

Note: For the specific use case at hand, indirect expansion is the simpler solution.

var='value'

declare -n varAlias='var'  # $varAlias is now another name for $var

echo "$varAlias" # -> 'value' - same as $var

The advantage of this approach is that the nameref is effectively just an another name for the original variable (storage location), so you can also assign to the nameref to update the original variable:

varAlias='new value'  # assign a new value to the nameref

echo "$var" # -> 'new value' - the original variable has been updated

See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameters.html


Compatibility note:

  • Indirect expansion and namerefs are NOT POSIX-compliant; a strictly POSIX-compliant shell will have neither feature.
  • ksh and zsh have comparable features, but with different syntax.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!