Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash ${!variable}

Tags:

bash

I am scratching my head on this one, can't find the bash reference talking about it.

In the code below

host_color=${uphost}_host_color
host_color=${!host_color}

What is the second line doing ? what does the !operator do in this case ?

like image 271
Olivier Refalo Avatar asked Apr 25 '12 13:04

Olivier Refalo


2 Answers

That is a short form for indirect references.

$ foo=bar
$ bar=bas
$ echo ${!foo}
bas

The seemingly similar construction ${!foo*} expands to the names of all variables whose name begin with foo:

$ foo1=x
$ foo2=y
$ echo ${!foo*}
foo1 foo2
like image 159
Anders Lindahl Avatar answered Sep 23 '22 21:09

Anders Lindahl


From the bash manual:

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. 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. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below.

like image 32
Eugene Yarmash Avatar answered Sep 24 '22 21:09

Eugene Yarmash