Operating System - HP-UX
1830935 Members
2278 Online
110017 Solutions
New Discussion

Re: script issue regarding variables

 
SOLVED
Go to solution
System and Database
Frequent Advisor

script issue regarding variables

Hello,
I'm writing a script and I have a problem with variables assignements. Here is what I want to do :

#!/usr/bin/sh
LISTE_USER1="john gérard raoul"
LISTE_USER2="vincent gaston"
for USER in ${LISTE_$1}
do
.....

And the script is meant to be called with a variable : for example
# script.sh USER1

The problem is that ${LISTE_$1} doesn't work.
I get a "bad substitution" error message.

Do you have a solution for this ?

Thanks,
T
5 REPLIES 5
Ralph Grothe
Honored Contributor

Re: script issue regarding variables

try

for USER in LISTE_$1; do
echo \$$USER
done

do something useful instead of echo in the loop body with the variable
Madness, thy name is system administration
Ralph Grothe
Honored Contributor

Re: script issue regarding variables

forgot,
to have the loop variable evaluated in a command you might prepend the "eval" command in your loop body where you reference the variable USER.
Madness, thy name is system administration
Christian Gebhardt
Honored Contributor
Solution

Re: script issue regarding variables

Hi

as Ralph said "eval" is the key

#!/usr/bin/sh
LISTE_USER1="john gG8rard raoul"
LISTE_USER2="vincent gaston"
for USER in `eval echo \\$LISTE_\$1`
do
echo $USER
done


Chris
Mark Grant
Honored Contributor

Re: script issue regarding variables

Personally I'd use arrays such as

LISTE_USER[1]="john grard raoul"
LISTE_USER[2]="vincent gaston"
for USER in ${LISTE_USER[$1]}
do
echo $USER
done


Obviously this then gets called with arguments of 1, 2 etc
Never preceed any demonstration with anything more predictive than "watch this"
System and Database
Frequent Advisor

Re: script issue regarding variables

Thank you all for your answers ! I didn't know the "eval" command.
Tom