为什么“[1> 2]”评估为True?

时间:2017-12-14 08:38:40

标签: linux bash

我有两个文件:
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            

你能说一下这怎么可能吗?

3 个答案:

答案 0 :(得分:4)

[也是Bash中的一个命令,因此[ 1 > 2 ][ 1 ] > 2相同,后者会成功并创建名为2的文件。

正如其他人指出的那样,你需要使用以下语法来比较整数:

[ 1 -gt 2 ]
[[ 1 -gt 2 ]]
(( 1 > 2 ))

答案 1 :(得分:3)

您应该在-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 string为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

答案 2 :(得分:1)

尝试使用此代码:

#!/bin/bash

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

-gt将继续进行数字比较,而不是ASCII。

相关问题