-1

I simulated the situation where the value of variable bar is $foo. foo is a variable too, which has the value hello.

$ foo=hello
$ bar=$(echo "\$foo")
$ echo $bar
$foo

How I can get to hello, given foo="hello" and bar="$foo"?

I tried:

$ echo $(echo $bar)

But the output still is:

$foo
3

2 Answers 2

4

use a "nameref"

declare -n bar=foo

foo=hello
echo "$bar"    # => hello

foo=world
echo "$bar"    # => world

Or an indirect variable

unset bar
bar=foo

foo=hello
echo "${!bar}"    # => hello

foo=world
echo "${!bar}"    # => world
2

Use eval like this:

$ foo=hello
$ bar=$(echo "\$foo")
$ echo "$bar"
$foo
$ eval echo "$bar"
hello
$ foo=world
$ eval echo "$bar"
world

In the above example, the eval bash builtin command will parse the arguments once more, so that the $bar variable contents will be interpreted once more as a variable ($foo) and its current contents (hello in the first case and world in the second case) will be used as the argument to the echo command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .