我有两个文件:
f1.txt:

1

dest/f1.txt:
1
2

当我在linux终端上的两个文件上都运行wc -l时,我得到了预期的结果:
$ wc -l < f1.txt
$ 1
$ wc -l < dest/f1.txt
$ 2

但是当我运行以下.sh文件时:
#!/bin/bash

    if [ $(wc -l < f1.txt) > $(wc -l < dest/f1.txt) ]; then
        echo -e "f1 has more lines"
    else
        echo -e "f1 doesn't have more lines"
    fi

输出为:
f1 has more lines

您能解释一下这怎么可能吗?

最佳答案

您应该在-gt子句中将if用于整数比较

如果使用><,则最终会进行 ASCII字母顺序比较

整数比较
-eq等于

if [ "$a" -eq "$b" ]
-ne不等于
if [ "$a" -ne "$b" ]
-gt大于
if [ "$a" -gt "$b" ]
-ge大于或等于
if [ "$a" -ge "$b" ]
-lt小于
if [ "$a" -lt "$b" ]
-le小于或等于
if [ "$a" -le "$b" ]
<小于(双括号中的)
(("$a" < "$b"))
<=小于或等于(双括号
中的)
(("$a" <= "$b"))
>大于(双括号
中的)
(("$a" > "$b"))
>=大于或等于(双括号
中的)
(("$a" >= "$b"))

字符串比较
=等于
if [ "$a" = "$b" ]

警告
请注意,将空白框定为=

if [ "$a"="$b" ] is not equivalent to the above.
==等于
if [ "$a" == "$b" ]

这是=的同义词。
Note
The == comparison operator behaves differently within a double-brackets test than within single brackets.
[[ $a == z* ]]   # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

[ $a == z* ]     # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
!=不等于
if [ "$a" != "$b" ]

该运算符在[[ ... ]]构造中使用模式匹配。
<小于,按ASCII字母顺序
if [[ "$a" < "$b" ]]

if [ "$a" \< "$b" ]

注意,"<"需要在[ ]构造中转义。
>大于,按ASCII字母顺序
if [[ "$a" > "$b" ]]

if [ "$a" \> "$b" ]

Note that the ">" needs to be escaped within a [ ] construct.
-z字符串为null,即长度为零
String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.

-n
string is not null.

资料来源:http://tldp.org/LDP/abs/html/comparison-ops.html

关于linux - 为什么 “[ 1 > 2 ]”评估为True?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47809065/

10-12 14:30
查看更多