The Gilbert Arenas Dagger
The Gilbert Arenas Dagger

Reputation: 12751

Bash Script - Exclamation Point within Variable Reference

I'm looking over a script (which has been used successfully in the past) which contains the following:

node=1
while :
do
    userKey=WEB_${node}_USER
    userVal=`echo ${!userKey}`

I have not been able to figure out why an exclamation point would be added to a variable reference like this. What purpose does "!" serve in this context?

It's rare for me to do much scripting so if I am missing any details please let me know and I will try to provide more information. I have not been able to find this answer elsewhere.

Thanks in advance!

Upvotes: 1

Views: 3437

Answers (2)

Sagar.P.Waghmare
Sagar.P.Waghmare

Reputation: 11

In bash, I thought that the only characters that retained their meta-character status inside double quotes were the dollar sign ($), the back-tick (`) and the backslash (\).

Upvotes: -1

chepner
chepner

Reputation: 532238

It's called indirect parameter expansion. Where $userKey expands to the value of the variable userKey, ${!userKey} expands to the value of the variable whose name is the value of userKey. Since usrKey has the value WEB_1_USER (given the current value of $node, ${!userKey} expands to the same result as $WEB_1_USER.

Its use is somewhat rare, since in many cases (including, it appears, here) an array WEB_USER of user names would be clearer than a set of numbered variables.

WEB_USER=(alice bob charlie)

node=1
while :
do
  userVal=${WEB_USER[node]}

Upvotes: 7

Related Questions