4楼,]前面没加空格报的错是missing ]
这个问题实际上有点复杂。
首先[或test命令有两种情况,一种是coreutils包里的独立程序,另外一种是某些shell(比如bash)的内置命令
两者在细节上有所不同。你可以用
来看到你输入的[或test到底是那种
如果是独立程序版的,可以通过manpage来看
……
-n STRING
the length of STRING is nonzero
STRING equivalent to -n STRING
-z STRING
the length of STRING is zero
STRING1 = STRING2
the strings are equal
STRING1 != STRING2
the strings are not equal
……
上面第一处红字部分明确说明了如果仅仅是一个字符串,等价于用-n来判断字符串是否为空。所以,在独立程序的[或test看来,[ "$yn"=="Y" ]就是判断"$yn"=="Y"这个字符串是否为空。记住字符串并不需要用"或'整体包起来,只包部分也可以的。
第二处红字说明了判断字符串相等要用=,而并没有提到==的用法。不过呢,实际上还是要看程序版本。manpage最后的SEE ALSO提到了一句info coreutils 'test invocation',你可以用这个来看进一步的信息。
如果info的输出中有
* String tests:: -z -n = == !=
说明支持==比较
如果是
* String tests:: -z -n = !=
说明不支持==比较
我稍微测试了一下,ubuntu 10.04的coreutils包版本是7.4,不支持==。ubuntu 12.04 LTS是8.13,支持==。你可以用
代码: 全选
/usr/bin/[ --version
来看程序的版本号
如果是shell内置的命令,就要查shell的manpage了,以bash为例
SHELL BUILTIN COMMANDS一节中的说明摘抄如下
test expr
[ expr ]
Return a status of 0 (true) or 1 (false) depending on the evalu‐
ation of the conditional expression expr. Each operator and op‐
erand must be a separate argument. Expressions are composed of
the primaries described above under CONDITIONAL EXPRESSIONS.
test does not accept any options, nor does it accept and ignore
an argument of -- as signifying the end of options.
叫你去看CONDITIONAL EXPRESSIONS。CONDITIONAL EXPRESSIONS一节中又有如下内容
string
-n string
True if the length of string is non-zero.
string1 == string2
string1 = string2
True if the strings are equal. = should be used with the test
command for POSIX conformance. When used with the [[ command,
this performs pattern matching as described above (Compound Com‐
mands).
同样说单独的字符串等价于用-n判断。但bash内置的[或test命令=和==两种比较都支持
所以估计楼主用的是较低版本的独立程序版[,不支持==比较