what does ! (exclamatory) mark inside curly braces ({}) when using variable in unix [duplicate]

旧巷老猫 提交于 2020-06-28 02:10:39

问题


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}

what is the difference? for me second option is not working , if i echo second option returns empty.


回答1:


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

From the bash man page:

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) 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.



来源:https://stackoverflow.com/questions/47592506/what-does-exclamatory-mark-inside-curly-braces-when-using-variable-in-u

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!