首页 > 解决方案 > 这是否等同于测试变量的存在?

问题描述

我正在挖掘我的 Mac 上的一些系统文件。在/etc/profile我发现以下摘录:

 if [ "${BASH-no}" != "no" ]; then
        [ -r /etc/bashrc ] && . /etc/bashrc
 fi

我已经尝试echo "${x-no}"过各种选择,x似乎它正在打印任何存在的值xx即已设置),no否则。

这让我想知道:这个条件是否只是测试变量x是否已设置?

进一步的问题:具体-做什么?有没有更好的方法来测试变量是否已设置?

标签: bash

解决方案


这个条件是否只是测试变量 x 是否已设置?

是的,尽管它在不太可能发生的情况下会感到困惑BASH=no

究竟是做什么的?

这是man bash

[...] Omitting the colon results in a test only for a parameter that is  un‐set.

   ${parameter:-word}
         Use Default Values.  If parameter is unset or null (see above),
         the expansion of word is substituted. Otherwise, the
         value of parameter is substituted.

有没有更好的方法来测试变量是否已设置?

是的:[ -v BASH ]。但是,这是特定于 bash 的,因此它违背了在执行特定于 bash 的操作之前检查当前 shell 是否为 bash 的目的。


推荐阅读