views:

27

answers:

1

In the following, I would like check if a given variable name is set:

$ set hello
$ echo $1
hello
$ echo $hello

$ [[ -z \$$1 ]] && echo true || echo false
false

Since $hello is unset, I would expect the test to return true. What's wrong here? I would assume I am escaping the dollar incorrectly.
TYIA

A: 

You are testing if \$$1 is empty. Since it begins with a $, it is not empty. In fact, \$$1 expands to the string $hello.

You need to tell the shell that you want to treat the value of $1 as the name of a parameter to expand.

  • With bash: [[ -z ${!1} ]]

  • With zsh: [[ -z ${(P)1} ]]

  • With ksh: tmp=$1; typeset -n tmp; [[ -z $tmp ]]

EDIT: better ksh solution courtesy of Dennis Williamson

Gilles
Another way in `ksh`: `typeset -n tmp; tmp=$1; [[ -z $tmp ]] ...` (I like to avoid `eval` as much as possible (even though it's safe in this particular circumstance).
Dennis Williamson
@Dennis: thanks, it's good to know there's a way in ksh too (and I don't like `eval` either, but it's the only portable way).
Gilles
Thank you both.
tlvince