[Nottingham] bash scripting - gotme

Johannes Kling jok at printk.net
Wed Oct 13 13:00:57 BST 2004


Hello,

> I guess the simplified version is; 'how do you get bash to read a string 
> as a variable name?'

bash has an eval function which comes in very handy in this case. It's
explained in bash's man page, if you want the exact details, but the
code snippet should make it obvious how it could be used in this case.
----
#!/bin/bash

## Declare the variables (directories)
foo1="foo"
foo2="bar"
foo3="baz"

c=1; # $c needs to be initialised
current=""; # $current strictly speaking doesn't

## We check whether the variable is empty. This should be reliable
## enough as a test to see whether the variable exists.
while eval 'test ! -z $foo'$c ; do
    ## Set current to be variable fooN
    eval 'current=$foo'$c
    echo "Foo of $c is $current";
    # increase $c by one
    c=$[c+1]
done
----

The above will print:
Foo of 1 is foo
Foo of 2 is bar
Foo of 3 is baz

and then exit. Adding a "foo4=qux" to the beginning will work as
expected.

Quoting the directories if they contain spaces or other funny
characters is left as an exercise for the reader :-).

Regards,
  Jo

-- 
"It's not peer pressure, it's just your turn!"




More information about the Nottingham mailing list