Bash 用 > 或 < 比较相同的字符串
Bash identical string comparison with > or <
为什么这行代码会打印出来?
if [ "a" < "a" ]; then echo wow; fi
还有这一行:
if [ "a" > "a" ]; then echo woow; fi
你不是在比较字符串。 <
是重定向运算符,因此实际上您正在检查此类操作是否成功。它是有效的,因为你碰巧在目录中有一个文件 a
你是 运行 命令!
看看如果文件 a
不存在会发生什么:
$ [ "a" < "a" ] && echo "yes"
bash: no such file or directory: a
让我们创建它并再次检查:
$ touch a
$ [ "a" < "a" ] && echo "yes"
yes
如果您想这样做,请使用 [[
。来自 3.2.4.2 Conditional Constructs:
[[…]]
When used with [[, the < and > operators sort lexicographically using
the current locale.
$ [[ "a" < "a" ]] && echo "yes" || echo "no"
no
要阻止 bash 将 <
和 >
解释为管道,您可以使用反斜杠对它们进行转义,或者像对所有其他字符串一样用引号将其括起来。
if [ "a" \< "a" ]; then echo "wow"; fi;
if [ "a" "<" "a" ]; then echo "wow"; fi;
[
又名 test
命令会将其参数解释为字符串,就像任何其他 unix 命令一样。请注意,这不会解析为真,因为它们相等,因此无法按词法排序。您需要自己包含相等性。
if [ "a" \< "a" ] || [ "a" = "a" ]; then echo "wow"; fi;
<
和 >
运算符不是 POSIX specification of test 的一部分,因此它是一个 shell-specific 功能,可能无法正常工作或与其他 shell 实现。
为什么这行代码会打印出来?
if [ "a" < "a" ]; then echo wow; fi
还有这一行:
if [ "a" > "a" ]; then echo woow; fi
你不是在比较字符串。 <
是重定向运算符,因此实际上您正在检查此类操作是否成功。它是有效的,因为你碰巧在目录中有一个文件 a
你是 运行 命令!
看看如果文件 a
不存在会发生什么:
$ [ "a" < "a" ] && echo "yes"
bash: no such file or directory: a
让我们创建它并再次检查:
$ touch a
$ [ "a" < "a" ] && echo "yes"
yes
如果您想这样做,请使用 [[
。来自 3.2.4.2 Conditional Constructs:
[[…]]
When used with [[, the < and > operators sort lexicographically using the current locale.
$ [[ "a" < "a" ]] && echo "yes" || echo "no"
no
要阻止 bash 将 <
和 >
解释为管道,您可以使用反斜杠对它们进行转义,或者像对所有其他字符串一样用引号将其括起来。
if [ "a" \< "a" ]; then echo "wow"; fi;
if [ "a" "<" "a" ]; then echo "wow"; fi;
[
又名 test
命令会将其参数解释为字符串,就像任何其他 unix 命令一样。请注意,这不会解析为真,因为它们相等,因此无法按词法排序。您需要自己包含相等性。
if [ "a" \< "a" ] || [ "a" = "a" ]; then echo "wow"; fi;
<
和 >
运算符不是 POSIX specification of test 的一部分,因此它是一个 shell-specific 功能,可能无法正常工作或与其他 shell 实现。