Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

var="Test"

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

#!/bin/bash

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

returns this output:

Hi

Bye

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.

share|improve this question

closed as unclear what you're asking by Patrick, slm, Gilles, Anthon, Thomas Nyman May 13 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.

8  
Err... just echo var? –  Braiam May 12 at 18:14
4  
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 at 18:15
2  
I think you've missed the drift of the SO solution; try var=Test; Test=SO; echo ${!var} –  1_CR May 12 at 18:22
    
I don't get it too but it's what are you trying to do? echo '$var' –  Renan Vicente May 12 at 19:50

2 Answers 2

up vote 4 down vote accepted

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 ...

share|improve this answer
    
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 at 21:31

Here's an even shorter one:

echo \$var
share|improve this answer

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