What does “${!var}” mean in shell script? [duplica

2019-05-07 12:24发布

This question already has an answer here:

I have a code block with below condition, not sure what exactly it does.

$var = "${args}_Some_Text"
if [ "${!var}"  == '' ];then
     echo "$var is not defined !!!"
fi 

1条回答
Luminary・发光体
2楼-- · 2019-05-07 12:47

This is called variable indirect expansion.

$ hello="this is some text"   # we set $hello
$ var="hello"                 # $var is "hello"
$ echo "${!var}"              # we print the variable linked by $var's content
this is some text

As you see, it is a way to define "variable variables". That is, to use variables whose content is the name of another variable.

From Bash Reference Manual → 3.5.3 Shell Parameter Expansion:

If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

查看更多
登录 后发表回答