问题
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