Problema de variable de script de shell

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

preguntado el 05 de mayo de 10 a las 08:05

3 Respuestas

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

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

contestado el 05 de mayo de 10 a las 14:05

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:

echo ${var[$i]}

contestado el 05 de mayo de 10 a las 13:05

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

contestado el 05 de mayo de 10 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.