做什么!在 unix 中使用变量时(感叹号)在花括号 ({}) 内标记 [英] what does ! (exclamatory) mark inside curly braces ({}) when using variable in unix
问题描述
让 var 成为一个变量,并为其分配一个值 /home/user 如下
Let var be a variable and it assigned a value /home/user as below
var=/home/user
当使用这个变量时,我看到它使用以下两种格式,
when using this variable, i have seen it using both of the below format,
1) cd ${var}
2) cd ${!var}
有什么区别?对我来说,第二个选项不起作用,如果我 echo 第二个选项返回空.
what is the difference? for me second option is not working , if i echo second option returns empty.
推荐答案
在这种情况下,是间接扩展(a),将 var
变量扩展以创建另一个变量名称,然后 那个 再次展开以获得最终结果:
In this case, it's indirect expansion(a), the var
variable is expanded to create another variable name and then that is expanded again to get your eventual result:
pax$ abc=def
pax$ def=ghi
pax$ echo ${abc} # abc -> def, one level.
def
pax$ echo ${!abc} # abc -> def -> ghi, two levels.
ghi
来自 bash
手册页:
如果参数的第一个字符是感叹号 (!),则它引入了一个变量间接级别.Bash 使用由参数的其余部分形成的变量的值作为变量的名称;这个变量然后被扩展,并且该值用于替换的其余部分,而不是参数本身的值.这称为间接扩展.
If the first character of parameter is an exclamation point (!), 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.
<小时>
(a) 它可以在其他情况下产生其他更复杂的效果,例如当您使用 ${!prefix*}
或 ${!name[@]}
但你的情况更简单.
(a) It can have other more complex effects in other situations, such as when you use ${!prefix*}
or ${!name[@]}
but your case is the simpler one.
这篇关于做什么!在 unix 中使用变量时(感叹号)在花括号 ({}) 内标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!