In the following, 开发者_如何学PythonI 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.
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 ]]Portably:
eval "tmp=\$$1"; [ -z "$tmp" ]
(Note that these will treat unset and empty identically, which is usually the right thing.)
加载中,请稍侯......
精彩评论