我刚在bash手册中发现了这个片段:
A variable may be assigned to by a statement of the form
name=[value]
If value is not given, the variable is assigned the null string.
什么是 "null string"?例如,
null string
代表什么?它与空字符串有何不同?local empty
等同于
local empty=""
?
我刚在bash手册中发现了这个片段:
A variable may be assigned to by a statement of the form
name=[value]
If value is not given, the variable is assigned the null string.
null string
代表什么?它与空字符串有何不同?local empty
local empty=""
?
#!/bin/bash
go(){
local empty
local empty2=""
[[ -z $empty ]] && echo "empty is null"
[[ -z $empty2 ]] && echo "empty2 is null"
[[ $empty == $empty2 ]] && echo "They are the same"
}
go
输出:
empty is null
empty2 is null
They are the same
test
有不同的表达式来测试一个字符串是否为空字符串([ <string> ]
)和是否具有非零长度([ -n <string> ]
),你可以通过比较 [ ] && echo "true"
的输出和 [ -n ] && echo "true"
的输出来看出它们之间的区别。” - kirelagin[ -n ]
并没有使用 -n
作为操作数,而是使用了测试的第一种形式来测试字符串 "-n"。尽管如此,在 Bash 文档中有些地方似乎明确提到了空字符串和空值字符串,并列在同一个句子中,这对我来说意味着它们是不同的。或者我希望在文档中看到一些支持“空字符串”与“空值字符串”相同的说法的内容。 - kirelagin
local empty
并不总等同于local empty=""
。例如,如果启用了set -u
,那么在第一种情况下,对$empty
的引用将失败,而在第二种情况下则不会。 - wjandrea