views:

53

answers:

3

Hi all,

I'm trying to write a shell script to automate a job for me. But i'm currently stuck. Here's the problem :

I have a variable named var1 (a decreasing number from 25 to 0 and another variable named var${var1} and this equals to some string. then when i try to call var${var1} in anywhere in script via echo it fails. I have tried $[var$var1], ${var$var} and many others but everytime it fails and gives the value of var1 or says operand expected error. Thanks for your help

+1  A: 

There's only one round of variable expansion, so you can't do it directly. You could use eval:

eval echo \${var$var1}

A better solution is to use an array:

i=5
var[$i]='foo'
echo ${var[$i]}
outis
A: 

It sounds like you need bash variable indirection. Take a look at the link below.

http://mywiki.wooledge.org/BashFAQ/006

Paul
+1  A: 

It's probably better if you use an array, but you can use indirection:

var25="some string"
var1=25
indirect_var="var$var1"
echo ${!indirect_var}    # echoes "some string"
Dennis Williamson