zsh:未定义变量时引发错误

zsh: raise error when variable not defined

zsh(或一般的 shell 脚本)的一个令人讨厌的方面是,如果您输入错误的变量名称,并且生成的名称不存在,它会被静默地视为空字符串,这使错误难以发现:

if somecondition
then
  myvar=55
else
  my_var=66
fi
echo $MyVar # Oops

我知道这条规则的存在是为了与优秀的老伯恩 shell 兼容。我也知道我可以在访问变量时明确捕获此错误:

echo ${MyVar?NOT SET}

但是如果我在每次访问变量时都这样做,会导致代码难看。由于我有显式初始化所有变量的习惯,因此我正在寻找一种方法,当访问 shell 变量或环境变量时,zsh 会自动溢出一条错误消息,但尚未设置。有没有办法做到这一点?我已经检查了 zshoptions 手册页,但没有找到合适的内容。

不仅在 zsh 中,在其他 shell 中也是如此,set -u 使对未设置变量的引用成为错误。

也就是说,许多脚本在使用此选项时将无法正常工作:[[ $foo ]] 不能再用于检查 foo 是否由外部环境提供,需要 [[ ${foo-} ]]相反。

为了说明 Charles Duffy 的答案,并作为此类测试的示例(在 zsh shell 中),当使用 nounset 时,您可以考虑这个 git 提交(对于 git 本身):
参见 commit 34d8f5a (06 Jun 2016) by Ville Skyttä (scop)
(由 Junio C Hamano -- gitster -- in commit 8162401 合并,2016 年 7 月 6 日)

git-prompt.sh: Don't error on null ${ZSH,BASH}_VERSION, $short_sha

When the shell is in "nounset" or "set -u" mode, referencing unset or null variables results in an error.
Protect $ZSH_VERSION and $BASH_VERSION against that, and initialize $short_sha before use.

-   [ -z "$ZSH_VERSION" ] || [[ -o PROMPT_SUBST ]] || ps1_expanded=no
+   [ -z "${ZSH_VERSION-}" ] || [[ -o PROMPT_SUBST ]] || ps1_expanded=no
                       ^
-   [ -z "$BASH_VERSION" ] || shopt -q promptvars || ps1_expanded=no
+   [ -z "${BASH_VERSION-}" ] || shopt -q promptvars || ps1_expanded=no