Suppose that I have a variable var in bash. I can assign a value to it. For example, I will make it a string:


I want to echo the name of var, not the value held by var. (I can do the latter with echo $var, but I actually want to do the former.)

The answer to this question from SO says to use echo ${!var}, but when I do that I echo just returns a blank line. For example, this bash script


echo "Hi"
echo ${!var}
echo "Bye"

returns this output:



with just a blank line between Hi and Bye, instead of var. What am I doing wrong?

I'm running bash 4.1.5(1) on Ubuntu 10.04.4.

closed as unclear what you're asking by Patrick, slm, Gilles, Anthon, Thomas Nyman May 13 '14 at 5:13

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 11
    Err... just echo var? – Braiam May 12 '14 at 18:14
  • 5
    I don't really understand the point of this. As @Braiam points out, since you are defining the name of the variable in the first place you will always know it and always be able to print it. What are you actually trying to do? – terdon May 12 '14 at 18:15
  • 3
    I think you've missed the drift of the SO solution; try var=Test; Test=SO; echo ${!var} – iruvar May 12 '14 at 18:22
  • I don't get it too but it's what are you trying to do? echo '$var' – Renan Vicente May 12 '14 at 19:50
  • I'm really curious, please tell us what did you need that for! – bubakazouba Dec 12 '16 at 18:23

The shell parameter expansion ${!name@} or ${!name*} could do the trick,

$ foo=bar
$ var_name=(${!foo@})
$ echo $var_name" = "$foo
foo = bar

Although feasible I can't imagine the utility of this ...

  • 1
    Note that if foo is not defined but foobar is, you'll get foobar. Other alternatives: var_name=${-+foo} (or ${foo+foo}), var_name=$'foo', var_name=$"foo" :-) – Stéphane Chazelas May 12 '14 at 21:31
  • If there were two variables visible, foo and foobar, both defined, the expression ${!foo@} would evaluate to foo foobar. As the answer remarks, its utility is hard to imagine. – CppNoob Mar 26 at 12:13

If you want to simply output a static variable name, you can escape the $-sign:

echo \$var
  • 2
    This should be the accepted solution. – David Poxon Dec 7 '15 at 0:22
  • 8
    Not at al!! This answer is not a good solution. This is going to simply output $var, but it's useless if the variable name is dynamic. For example, let's say you need to filter a set of environment variables starting with a PREFIX_, but you don't know about the size of the set or the variable names in it. The accepted solution is more suitable for this scenario. – Héctor Valverde Pareja Aug 9 '16 at 16:12

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