加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – ${var}和${var-}之间有什么区别

发布时间:2020-12-16 01:37:43 所属栏目:安全 来源:网络整理
导读:我已经看到一些 shell脚本使用这个变量引用表示法,我只是找不到任何信息. 就我的测试而言,它显然是一样的. 有线索吗? $uno=1$if [ -n "${uno}" ]; then echo yay!! ; fiyay!$if [ -n "${uno-}" ]; then echo yay!! ; fiyay! ${uno-}是在未设置参数uno的情
我已经看到一些 shell脚本使用这个变量引用表示法,我只是找不到任何信息.

就我的测试而言,它显然是一样的.

有线索吗?

$uno=1
$if [ -n "${uno}" ]; then echo yay!! ; fi
yay!
$if [ -n "${uno-}" ]; then echo yay!! ; fi
yay!
${uno-}是在未设置参数uno的情况下提供默认值的示例.

如果uno未设置,我们得到 – 后面的字符串:

$unset uno
$echo ${uno-something}
something

如果uno只是空字符串,则返回uno的值:

$uno=""
$echo ${uno-something}

$

如果uno具有非空值,当然,则返回该值:

$uno=Yes
$echo ${uno-something}
Yes

为什么要使用${variable-}?

当脚本的正确操作很重要时,脚本编写者通常使用set -u,它会在使用unset变量时生成错误消息.例如:

$set -u
$unset uno
$echo ${uno}
bash: uno: unbound variable

要处理可能要禁止此消息的特殊情况,可以使用尾随 – :

$echo ${uno-}

$

[信用发现OP的full code使用了-u及其对这个问题的重要性归于Benjamin W.]

文档

来自man bash

When not performing substring expansion,using the forms documented
below (e.g.,:-),bash tests for a parameter that is unset or null.
Omitting the colon results in a test only for a parameter that is
unset.

${parameter:-word}
Use Default Values. If parameter is unset or null,the expansion of word is substituted. Otherwise,the value of parameter is substituted. [emphasis added]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读