Shell script variable problem

I am trying to write a shell script to automate things for me. But I'm stuck now. Here's the problem:

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

+2


a source to share


3 answers


It's probably better if you're using an array, but you can use indirect actions:



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

      

+2


a source


There is only one round of variable expansion, so you cannot do it directly. You can use eval

:

eval echo \${var$var1}

      



The best solution is to use an array:

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

      

+1


a source


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

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

0


a source







All Articles