如何检查zsh中是否设置了变量?

如何检查zsh中是否设置了变量?,zsh,Zsh,测试zsh中是否设置了变量的规范/惯用方法是什么 if ....something.... ; then print "Sweet, that variable is defined" else print "That variable is not defined" fi 以下是在Zsh中执行此操作的典型方法: if (( ${+SOME_VARIABLE} )); then 例如: if (( ${+commands[brew]} )); then brew in

测试zsh中是否设置了变量的规范/惯用方法是什么

if ....something.... ; then
    print "Sweet, that variable is defined"
else
    print "That variable is not defined"
fi

以下是在Zsh中执行此操作的典型方法:

if (( ${+SOME_VARIABLE} )); then
例如:

if (( ${+commands[brew]} )); then
    brew install mypackage
else
    print "Please install Homebrew first."
fi
在Zsh 5.3及更高版本中,可以在条件表达式中使用
-v
运算符:

if [[ -v SOME_VARIABLE ]]; then
POSIX兼容测试将是

if [ -n "${SOME_VARIABLE+1}" ]; then
在条件表达式中使用
-v
(在
zsh
5.3中介绍)运算符

% unset foo
% [[ -v foo ]] && echo "foo is set"
% foo=
% [[ -v foo ]] && echo "foo is set"
foo is set

可能是重复的哈。我的意思是,只有zsh语法,但是POSIX sh语法在这里也可以工作。编辑以澄清。Bash问题没有提供规范的zsh语法。在
Bash
引入
-v
操作符(zsh也支持
zsh
操作符,请参见我的答案)之前,链接的问题被问到(并且大部分得到了回答)。
Bash
的库存版本除了与POSIX兼容的shell之外,实际上没有任何用处;它已经过时多年了<代码>/bin/zsh在OS X Sierra中应为5.2。在zsh 5.2:zsh:unknown condition中不适用于我:-v@chepner那不应该是
-n
,而不是
-z
-z
是相反的。检查是否设置了变量(即使是空值)的可移植方法:
isset(){[[$(eval echo“\${${1}+1}”)];}