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
You are testing if
\$$1is empty. Since it begins with a$, it is not empty. In fact,\$$1expands to the string$hello.You need to tell the shell that you want to treat the value of
$1as 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 ]]Portably:
eval "tmp=\$$1"; [ -z "$tmp" ](Note that these will treat unset and empty identically, which is usually the right thing.)