How to use echo output as a variable
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
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.