4

I pass a string as an argument to a shell script. and the shell script should tell me if the passed argument is a variable

something like this

if [ ! -z ${$1} ] ; then  
echo yes! $1 is a variable and its value is ${$1}  
fi

but this gives me bad substitution err..

I definitely know i'm missing something.. help me out!

Eg usage:

$ myscript.sh HOME  
yes! HOME is a variable and its value is /home/raj
Mat
  • 202,337
  • 40
  • 393
  • 406
raj
  • 3,769
  • 4
  • 25
  • 43

2 Answers2

4

The syntax for this is:

${!VAR}

Example:

$ function hello() { echo ${!1}; }
$ hello HOME
/home/me
Mat
  • 202,337
  • 40
  • 393
  • 406
1

Found it here: http://www.linuxquestions.org/questions/programming-9/bash-how-to-get-variable-name-from-variable-274718/

All you should do:

if [ ! -z ${!1} ]; then
    echo yes $1 is a variable and its value is ${!1}
fi
pkk
  • 3,691
  • 2
  • 21
  • 29