shell 脚本中的“${!var}”是什么意思?
What does "${!var}" mean in shell script?
我有一个代码块具有以下条件,不确定它到底做了什么。
$var = "${args}_Some_Text"
if [ "${!var}" == '' ];then
echo "$var is not defined !!!"
fi
这叫做变量间接展开。
$ 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
如你所见,它是定义"variable variables"的一种方式。即使用内容为另一个变量名的变量。
来自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.
我有一个代码块具有以下条件,不确定它到底做了什么。
$var = "${args}_Some_Text"
if [ "${!var}" == '' ];then
echo "$var is not defined !!!"
fi
这叫做变量间接展开。
$ 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
如你所见,它是定义"variable variables"的一种方式。即使用内容为另一个变量名的变量。
来自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.