我最近在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?
发布评论
评论(1)
实际上,文档确实说明了这里发生的事情,:
在实践中,这意味着如果变量不设置,它们的行为方式相同:
但是,如果变量设置为空字符串,则行为是不同的。带有结肠的表达式将设置变量并返回该值,而没有的值将以IS(即设置为空字符串)将变量留下的值,并返回其空值:
如文档中所述,相同的行为适用于另一个“运算符”(
-
,?
,+
)。以
Actually, the documentation does explain what is going on here, even if burying the lede a bit:
In practice, this means that they behave the same way if the variables are unset:
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:
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 :)