Re: Variable resolution in shell scripts

From: Jef Lee (jef.lee@ITVISION.COM.AU)
Date: Fri Jul 12 2002 - 05:03:43 EDT


The eval method is the most concise. If you test for invalid responses
beforehand.
Perhaps:

#!/bin/ksh

var_0="an invalid variation"
var_1="the first variation"
var_2="the second variation"
var_3="the third variation"
echo "Please enter selection(1, 2, or 3)"
read user_input debris
[ -n "${userinput}" ] && \
[ "${user_input}" -ge 1 -o "${user_input}" -le 3 ] 2>/dev/null || \
user_input=0
eval echo "User selected \${var_${user_input}}"

The debris picks up anything AFTER the first user word entered.
The test lines check for a) no input; b) input outside the 1-3 range.
Anything that does not pass the test sets the input to 0 which
is translated as an invalid selection.
Works every time.

Jef.

-----Original Message-----
From: Jean-Marc Monnez [mailto:monnez.jean-marc@AGORA.MSA.FR]
Sent: Friday, 12 July 2002 4:02 PM
To: aix-l@Princeton.EDU
Subject: Re: Variable resolution in shell scripts

I agree with Bill Thompson's suggestion of 'eval'. This way I should have
done
it.

Another interesting possibility when you need user response is the use of
specific ksh statement 'select'.
For your example, it could be :
-----------------------------------------------------
#!/bin/ksh
PS3="Your choice number ? "
select var in "first var" "second var" "third var"
do
    if [[ -n "$var" ]]
    then
        echo "User selected the ${var}iation"
        break
    fi
done
---------------------------------------------------------

Regards

-- JMM

Robert Bardos wrote :

> An easy one for most of you,
>
> given a piece of code like this:
>
> var_1="first var"
> var_2="second var"
> var_3="third var"
> read user_input
> # user enters "2"
> echo "User selected the ????iation"
> # expected result is: "User selected the second variation"
>
> Is there some kind of recursive variable resolution, ie. like
> $var_$user_input, that would resolve into the expected result and if yes,
> how would I have to code this?
>
> What book would you recommend for a beginner who wants to write some "more
> than trivial" shell scripts? (Or should I leave it at that and learn Pearl
> instead?)
>
> TIA
> Robert
>
> Sicherheitsmeldung: Diese Mitteilung ist ungeschuetzt und koennte waehrend
> der Uebermittlung von Dritten eingesehen und veraendert werden. Der
Absender
> uebernimmt deshalb fuer den Inhalt keine Haftung. Sollten Sie diese
> Mitteilung irrtuemlich erhalten haben, bitten wir Sie, den Absender zu
> informieren und die Mitteilung in Ihrem System zu loeschen.
>
> ------------------------------------------------------------------------
> Name: InterScan_Disclaimer.txt
> InterScan_Disclaimer.txt Type: Plain Text (text/plain)
> Encoding: quoted-printable



This archive was generated by hypermail 2.1.7 : Wed Apr 09 2008 - 22:16:03 EDT