2

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

3 Answers 3

2

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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]}

Comments

0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.