Operating System - HP-UX
1836603 Members
3590 Online
110102 Solutions
New Discussion

Re: variable substitution

 
SOLVED
Go to solution
Dave Peeke
Occasional Advisor

variable substitution

I am trying in a script to use a variable within a variable and I'm having trouble with the syntax e.g:

xxxa=test1
xxxb=test2
xxxc=test3
for i in a b c
do
echo "$xxx$i"
done

where I want the result to be test1, test2, test3 (not xxxa, xxxb, xxxc). Can anyone help me with the syntax for the echo line please?
9 REPLIES 9
Darrel Louis
Honored Contributor

Re: variable substitution

I've done a similar test:

a=test1
b=test2
c=test3
for i in $a $b $c
do
echo "$i"
done

The variables you should specify with $xxxa etc.

Is this what you want?
Dave Peeke
Occasional Advisor

Re: variable substitution

Darrel,

Not quite as I don't want to specify the whole variable in the for statement. The previously assigned variables need to be longer and I will actually be using a number to reference them in a loop i.e. disk1 disk2 disk3 etc and the loop count will be used for the number i.e. for i in 1 2 3 4.
Tom Danzig
Honored Contributor

Re: variable substitution

Try putting curly braces around the variable name. Required if the variable name adjoins additional text. Such as:

echo "${xxx}${i}"
Dave Peeke
Occasional Advisor

Re: variable substitution

Tom,

Thanks, but it doesn't fix the problem as I get a,b,c rather than the contents of xxxa, xxxb, xxxc.
Kenneth Platz
Esteemed Contributor
Solution

Re: variable substitution

This should work:

#!/bin/sh

xxxa="test 1"
xxxb="test 2"
xxxc="test 3"

for I in a b c
do
eval "echo \$xxx$I"
done
I think, therefore I am... I think!
Victor BERRIDGE
Honored Contributor

Re: variable substitution

I dont think you can echo a variable that is itself an echo of another, so I dont see any solution except Darrels,which mean you need a step between:
xxxa=test1
xxxb=test2
xxxc=test3

a=$xxxa
b=$xxxb
c=$xxxc
for i in $a $b $c
do
echo "$i"
done

Good luck

Victor
Pramod_4
Trusted Contributor

Re: variable substitution

Hi,

Assign the variable as follows:

xxx[1]=tiger ; xxx[2]=lion ; xxx[3]=cat


If you assign as above then the following would do the job:

for i in ${xxx[@]} ; do

echo $i

done


Above should display:
tiger
lion
cat


Best of luck,

Pramod
Alan Riggs
Honored Contributor

Re: variable substitution

I agree, this case seems quite appropriate for an array variable. You can even set teh variables easily using set -A
Shannon Petry
Honored Contributor

Re: variable substitution

Not that your problem is not fixed already.....Some good things were posted. Another thing I do occasionally is use a little used command "eval". I.E.
xxxa=1
xxxb=2
xxxc=3
for i in $a $b $c ; do
eval echo "\$xxx$i"
done

The eval tells the shell to expand all of the variables prior to excecuting the "echo".
This is why Kenneths example works!

Regards,
Shannon
Microsoft. When do you want a virus today?