我在做一些测试,我不明白为什么两个结果不同。第一个似乎是正确的,因为在新月顺序中,字符“f”比“F”先出现
$ [[ "Foo" < "foo" ]]
$ echo $?
1
那么为什么这个不正确呢?
$ [ "Foo" \< "foo" ]
$ echo $?
0
最佳答案
两者都是 [[
和 [
内置于 bash
. [
相当于 test
命令,也是一个内置命令。 (嗯,几乎等同;[
需要匹配的 ]
, test
不需要。)
根据 bash 手册:
When used with
test
or[
, the<
and>
operators sort lexicographically using ASCII ordering.
(Bourne shell 内置程序已记录 here)。
但是[[
中的表达式... ]]
遵循 Bash conditional expressions 的规则:
When used with
[[
, the<
and>
operators sort lexicographically using the current locale. Thetest
command uses ASCII ordering.
(作为 GNU coreutils 包的一部分提供了另一个 test
/[
命令,通常是 /usr/bin/test
。此命令不提供 <
和 >
运算符,它们不是由 POSIX 指定的。如果您使用的是 bash,则外部命令应该无关紧要,除非您明确给出完整路径 /usr/bin/test
。)
您的问题被标记为“bash”和“sh”。如果您使用的是 bash,您可能应该使用特定于 bash 的 [[
特征而不是 [
.如果你想要更好的可移植性(例如,如果你的脚本可能与 bash 以外的 shell 一起使用),你不能依赖 [[
内置,你不能假设 [
或 test
支持<
和 >
.
关于bash - [[ ]] 和 [] 字符串比较器 "<"的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40871736/