Problema de variable de script de shell
Frecuentes
Visto 330 equipos
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 Respuestas
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"
contestado el 05 de mayo de 10 a las 14:05
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]}
contestado el 05 de mayo de 10 a las 13:05
0
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 bash shell or haz tu propia pregunta.