Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "${!var}" mean in shell script? [duplicate]

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 
like image 681
tempuser Avatar asked Dec 02 '16 09:12

tempuser


1 Answers

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.

like image 107
fedorqui 'SO stop harming' Avatar answered Nov 14 '22 16:11

fedorqui 'SO stop harming'