在我的Linux Mint 17.2 中,/etc/bash.bashrc我看到以下内容:
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi
这是对令牌的第一次引用debian_chroot。
为什么这段代码使用${debian_chroot:-}而不是仅仅使用$debian_chroot?
Bash 的Shell 参数扩展说:
${参数:-word}
如果参数未设置或为空,则替换单词的扩展。否则,替换参数的值。
在这里,“word”是空的,那为什么还要用空来代替空呢?
${debian_chroot:-}如果 shell 正在运行set -u(使用未定义变量时崩溃)并且此时debian_chroot未设置,则该语法会阻止 shell 退出。
您不希望拥有普通的交互式 shell set -u(它很容易崩溃),但它在脚本中非常有用。
要看到这个:
bash -c 'set -u; [ -z $a ]; echo ok'          # error
bash -c 'set -u; a=; [ -z $a ]; echo ok'      # ok
bash -c 'set -u; [ -z ${a:-} ]; echo ok'      # ok
bash -c 'set -u; a=; [ -z ${a:-} ]; echo ok'  # ok