Another BASH Scripting question

D. Hugh Redelmeier hugh-pmF8o41NoarQT0dZR+AlfA at public.gmane.org
Mon Feb 9 19:17:20 UTC 2004


| From: Chris F.A. Johnson <c.f.a.johnson-bJEeYj9oJeDQT0dZR+AlfA at public.gmane.org>

| On Mon, 9 Feb 2004, D. Hugh Redelmeier wrote:
| 
| > | From: Chris F.A. Johnson <c.f.a.johnson-bJEeYj9oJeDQT0dZR+AlfA at public.gmane.org>
| > | On Mon, 9 Feb 2004, Madison Kelly wrote:
| >
| > |     Use eval:
| > |
| > | eval var=${server}_SNAT_IP
| > | echo "$var | { .......
| >
| > If I understand what you are suggesting, then it does not work:
| >
| >     $ server=SRV2
| >     $ SRV2_IB_TCP="22 80"
| >     $ eval var=${server}_SNAT_IP
| >     $ echo $var
| >     SRV2_SNAT_IP
| >
| > I think that this is closer to what is needed:
| >     $ eval z='$'${server}_IB_TCP
| >     $ echo $z
| >     22 80
| 
|     Right. I meant:
| 
| eval var=$\${server}_SNAT_IP

I don't think so:
    $ server=SRV2
    $ SRV2_IB_TCP="22 80"
    $ eval var=$\${server}_SNAT_IP
    $ echo $var
    23484{server}_SNAT_IP

I think you meant:
    $ eval var=\$${server}_IB_TCP
    $ echo $var
    22 80

This just shows how easy it is to make a mistake with this corner of
the language.  Test before publishing.

|     That what happens when I post before my first cup of coffee.

More coffee!

|     Exactly. I prefer the backslash.

Single quotes seem a little more explicit to me.  In this case, either
will do.

|     It can get pretty hairy using backslashes with eval, but if I need
|     more than 2 consecutive backslashes, I use a different syntax.

Backslashes come in quatities that are a power of two :-)

| > If I'd designed the Bourne Shell, the following would work:
| >
| >     $ echo ${${server}_IB_TCP}
| >     bash: ${${server}_IB_TCP}: bad substitution
| 
|      In bash, you can use:
| 
| v=${server}_SNAT_IP
| var=${!v}

Right.  I'd vaguely remembered this, but could not see it in the man
page.  The reason is that ! is written as "exclamation point" in that
section of the man page :-(

I avoid bashisms as much as possible, but this one looks like the best
approach.  It avoids the dreaded eval.

It does seem awkward compared with my design.  It requires an extra
variable and an extra statement.

Hugh Redelmeier
hugh-pmF8o41NoarQT0dZR+AlfA at public.gmane.org  voice: +1 416 482-8253


--
The Toronto Linux Users Group.      Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml





More information about the Legacy mailing list