1

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

and i want the value of x to be echoed with using y someting like this

a=`echo $(echo $y)`
echo $a

Ans 102

8
  • 2
    If you're using bash, then echo ${!y}. Commented Jun 9, 2010 at 15:42
  • this worked for me echo $(($y)) Commented Jun 9, 2010 at 15:48
  • 1
    that works if x is a number because $(( )) is arithmetic expansion. It will give 0 if x is some arbitrary string. Commented Jun 9, 2010 at 20:09
  • @KennyTM - that's an interesting feature. Do you know what bash calls that feature so I can read more about it? Commented Jun 9, 2010 at 22:41
  • @R Samuel Klatchko: "indirection" Commented Aug 25, 2010 at 16:34

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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).

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.