在我的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参数扩展说:
$ {parameter:-word}
如果参数未设置或为null,则替换单词的扩展名。否则,将替换参数的值。
在这里,“单词”为null,那么为什么还要用null代替null?
该语法${debian_chroot:-}
可防止外壳程序与之一起运行set -u
(使用未定义变量时崩溃),并且debian_chroot
在该位置未设置外壳程序。
您不希望普通的交互式外壳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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句