shell:当var未设置或为null时,$ {var:-}的用途是什么? [英] shell: What is the purpose of ${var:-} when var is unset or null?
问题描述
在我的/etc/bash.bashrc
我看到以下内容:
In my Linux Mint 17.2 /etc/bash.bashrc
I see the following:
# 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
的首次引用.
This is the first reference to the token debian_chroot
.
为什么此代码不使用 $ debian_chroot
而是使用 $ {debian_chroot:-}
?
Why does this code use ${debian_chroot:-}
instead of just $debian_chroot
?
Bash的 Shell参数扩展说:
$ {parameter:-word}
${parameter:-word}
如果参数未设置或为null,则替换单词的扩展名.否则,将替换参数的值.
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
在这里,单词"为null,那么为什么还要用null代替null?
Here, "word" is null, so why bother substituting null for null?
推荐答案
语法 $ {debian_chroot:-}
可以防止shell在运行 set -u 时退出.code>(使用未定义的变量时崩溃),并且此时未设置
debian_chroot
.
The syntax ${debian_chroot:-}
prevents the shell from exiting if it is running with set -u
(crash when using undefined variables) and debian_chroot
is unset at that point.
您不希望普通的交互式外壳具有 set -u
(它很容易崩溃),但是在脚本中可能非常有用.
You don't want a normal interactive shell to have set -u
(it would crash too easily), but it can be very useful in scripts.
要查看此内容
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
这篇关于shell:当var未设置或为null时,$ {var:-}的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!