gpt4 book ai didi

linux - shell:当 var 未设置或为 null 时,${var:-} 的用途是什么?

转载 作者:IT王子 更新时间:2023-10-29 01:25:52 26 4
gpt4 key购买 nike

在我的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

这是对 token debian_chroot 的第一次引用。

为什么这段代码使用 ${debian_chroot:-} 而不是仅仅使用 $debian_chroot

Bash 的 Shell Parameter Expansion说:

${parameter:-word}

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

在这里,“word”是空的,那么为什么要用空代替空呢?

最佳答案

语法 ${debian_chroot:-} 阻止 shell 在 set -u 运行时退出(使用 undefined variable 时崩溃)和 debian_chroot 此时未设置。

希望普通的交互式 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

关于linux - shell:当 var 未设置或为 null 时,${var:-} 的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38909081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com