2

Given a variable name is there a function that will print its value?

Often times I pass the name of a variable to a bash function and instead of doing the expansion while passing it I would like to expand it inside the function. Of course when I do this I end up having to create the string with the variable name then running exec. It would be much more succinct if I could just run a command that echoed the output!

1
  • Not sure what you mean. Can you provide an example?
    – forcefsck
    Oct 28, 2011 at 15:06

2 Answers 2

7
show_val() { echo "${!1}"; }
foo=bar
echo $(show_val foo)   # => bar
# works with arrays too
a=(zero one two)
echo $(show_val a[1])  # => one

Documented in the bash manual here

1
  • As always Ty for the guidance. Oct 28, 2011 at 18:48
1

Not sure what you mean in your question about "running exec". Perhaps you meant eval.

show_val() { eval echo \$$1; }
foo=bar
show_val foo

You must log in to answer this question.

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