1

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!

The Gilbert Arenas Dagger
  • 12,071
  • 13
  • 66
  • 80

2 Answers2

7

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]}
chepner
  • 497,756
  • 71
  • 530
  • 681
-1

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

rici
  • 234,347
  • 28
  • 237
  • 341
  • That's true but (a) irrelevant and (b) not an answer. (Irrelevant because the ! is part of a ${...} expansion, and the $'s metacharacter status is not in doubt.) – rici Aug 01 '14 at 18:09