cancel
Showing results for 
Search instead for 
Did you mean: 

Question about shell script

SOLVED
Go to solution
Gustavo Souza Lima
Frequent Advisor

Question about shell script

Hi guys,

I make a shell script and i want to do this:

VAR1="casa"
VAR2=1

echo $(echo VAR${VAR2})

The result is "VAR1" instead of "casa".

What was I doing wrong???

9 REPLIES
Shahul
Esteemed Contributor

Re: Question about shell script

Hi,

To me, it looks correct. It should echo "VAR1". If you want "casa1" to be echo'd, then the command should be
#echo $VAR1$VAR2

Good luck
Shahul
Patrick Wallek
Honored Contributor
Solution

Re: Question about shell script

Try this and see if it is what you want:


eval echo \${VAR${VAR2}}
Mark McDonald_2
Trusted Contributor

Re: Question about shell script

I think you would be better treating VAR1 as an array:

VAR[1]=casa
VAR2=1
echo ${VAR[$VAR2]}
Gustavo Souza Lima
Frequent Advisor

Re: Question about shell script

Shahul,

I want print the content of the variable VAR1.

My will is, in the first echo - (echo VAR${VAR2}) print VAR1 and with the second echo command - (echo $VAR1) print "casa".
Fredrik.eriksson
Valued Contributor

Re: Question about shell script

I believe Patrick is on the right track.
Variable expansion doesnt work that easy.
What you can do if you run bash or maybe ksh (not really sure actually) is the following.

#!/bin/bash
array[1]="Casa"
array[2]="Next thing"
array[3]="And so on"

ptr=1
echo ${array[$ptr]}
ptr=2
echo ${array[$ptr]}
ptr=3
echo ${array[$ptr]}

This also works when adding things.

x=0
for i in List of words; do
array[$x]=$i
let x=x+1
done

Best regards
Fredrik Eriksson
Mark McDonald_2
Trusted Contributor

Re: Question about shell script

You may be able to do something like:

typeset -n someVariable="VAR$VAR2"
not sure where to go with this now....

OR

Try what Patrick suggested.
Matti_Kurkela
Honored Contributor

Re: Question about shell script

echo $(echo VAR${VAR2})

expands step by step like this:

echo $(echo VAR${VAR2}) # original
=> echo $(echo VAR1) # ${VAR2} == 1
=> echo "VAR1" # $(echo VAR1) == "VAR1"
=> VAR1 # the output

If you want to use the value of the variable VAR2 as a part of the name of the variable you ultimately want, you would need a construct like this:

eval echo \${VAR${VAR2}}

=> eval echo ${VAR1} # backslash is removed, ${VAR2} == 1
=> echo casa # eval expands variables again, ${VAR1} == casa
=> casa

You will need "eval" to trigger a second pass of variable expansion, and the backslash to protect the first $ to remain unexpanded through the first expansion pass.

MK
MK
Gustavo Souza Lima
Frequent Advisor

Re: Question about shell script

thanks for the posts.
Patrick gave me a good solution.
Mark McDonald_2
Trusted Contributor

Re: Question about shell script

Nill points even for my suggestions, wont be helping you again.