echo value inside a variable?
x=102 y=x
means when i echo $y it gives x echo $y x --and not 102
and when i echo $x it give 102
lets say I dnt know what is inside y
开发者_Go百科and i want the value of x to be echoed with using y someting like this
a=`echo $(echo $y)`
echo $a
Ans 102
You need to tell the shell to evaluate your command twice -- once to turn $y into x, and again to get the value of $x. The most portable way I know to do this is with eval:
$ /bin/sh
$ x=100
$ y=x
$ echo $y
x
$ eval echo \$$y
100
$
(You need to escape the first $ in the eval line because otherwise the first evaluation will replace "$$" with the current pid)
If you're only concerned with bash, KennyTM's method is probably best.
In ksh 93 (I don't know whether this works in ksh 88):
$ x=102; typeset -n y=x
$ echo $x
102
$ echo $y
102
$ echo ${!y}
x
Confusingly, the last two commands do the opposite of what they do in Bash (which doesn't need to flag the variable using typeset
).
精彩评论