开发者

Escaping in test comparisons

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.

TYIA


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜