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!

  • Not sure what you mean. Can you provide an example? – forcefsck Oct 28 '11 at 15:06
6
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

  • As always Ty for the guidance. – Arcabard Oct 28 '11 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.