在bash中的参数溢出中,相等/减去符号没有结肠

发布于 2025-02-11 05:00:14 字数 398 浏览 1 评论 0 原文

我最近在bash脚本中找到了这样的片段:

$ echo ${A=3}

现在,我知道 $ {a:= 3} 将设置变量 a 如果 a 是“虚拟”,或 $ {a:-3} 如果 a 是“虚假”,则会返回3。我从未见过没有colon的这些类似的表情,我在 bash的文档

这里发生了什么?

I found a snippet like this in a Bash script recently:

$ echo ${A=3}

Now, I know that ${A:=3} would set the variable A if A is "falsy", or ${A:-3} would return 3 if A is "falsy." I have never seen these similar expressions without the colon though, and I cannot find the explanation for these colon-less expressions in the Bash's documentation.

What is going on here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绻影浮沉 2025-02-18 05:00:14

实际上,文档确实说明了这里发生的事情,

不执行下弦扩展时,使用下面描述的形式(例如': - '),对未设置或空的参数进行bash测试。 省略结肠仅导致对未设置的参数进行测试。 换句话说,如果包括结肠,则操作员对两个参数的存在进行测试,并且价值不是零;如果省略了结肠,则仅对存在的操作员进行测试。

在实践中,这意味着如果变量不设置,它们的行为方式相同:

$ echo ${A=no-colon}
no-colon
$ echo ${B:=with-colon}
with-colon
$ echo $A
no-colon
$ echo $B
with-colon

但是,如果变量设置为空字符串,则行为是不同的。带有结肠的表达式将设置变量并返回该值,而没有的值将以IS(即设置为空字符串)将变量留下的值,并返回其空值:

$ A='' ; B=''
$ echo ${A=no-colon}

$ echo ${B:=with-colon}
with-colon
$ echo $A

$ echo $B
with-colon

如文档中所述,相同的行为适用于另一个“运算符”( - +)。

Actually, the documentation does explain what is going on here, even if burying the lede a bit:

When not performing substring expansion, using the form described 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. Put another way, if the colon is included, the operator tests for both parameters’ existence and that its value is not null; if the colon is omitted, the operator tests only for existence.

In practice, this means that they behave the same way if the variables are unset:

$ echo ${A=no-colon}
no-colon
$ echo ${B:=with-colon}
with-colon
$ echo $A
no-colon
$ echo $B
with-colon

However, if the variables are set to the empty string, then the behavior is different. The expression with a colon will set the variable and return the value, and the one without will leave the variable as is (i.e., set to the empty string) and return its empty value:

$ A='' ; B=''
$ echo ${A=no-colon}

$ echo ${B:=with-colon}
with-colon
$ echo $A

$ echo $B
with-colon

As stated in the documentation, the same behavior applies to the other "operators" (-, ?, +).

Posting it in the spirit of Can I answer my own question? and because it took a surprisingly long time for me to learn it, even after finding it in code. Maybe making it a bit more explicit, with some examples, can help somebody else out there :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文