为什么" [1> 2]";评估为True? [英] Why "[ 1 > 2 ]" evaluates to True?

查看:71
本文介绍了为什么" [1> 2]";评估为True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件:
f1.txt:

I have two files:
f1.txt:

1

dest/f1.txt:

dest/f1.txt:

1
2

当我在linux终端上的两个文件上都运行wc -l时,我得到了预期的结果:

When I run wc -l on both of those files in linux terminal - I get my expected results:

$ wc -l < f1.txt
$ 1
$ wc -l < dest/f1.txt
$ 2

但是当我运行以下.sh文件时:

But when I run the following .sh file:

#!/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            

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

Can you explian how could this be possible?

推荐答案

您应该在if子句中使用-gt进行整数比较.

You should use the -gt for integer comparison in a if clause.

如果使用><,您将最终进行 ASCII字母顺序比较.

If you use > or < you will end up doing ASCII alphabetic order comparison.

整数比较

-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" ]

警告
请注意=的空白框架.

Caution
Note the whitespace framing the =.

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" ]

此运算符在[[ ... ]]构造中使用模式匹配.

This operator uses pattern matching within a [[ ... ]] construct.

< 小于,按ASCII字母顺序

< is less than, in ASCII alphabetical order

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

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

请注意,"<"需要在[ ]构造中转义.

Note that the "<" needs to be escaped within a [ ] construct.

> 大于,按ASCII字母顺序

> is greater than, in ASCII alphabetical order

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

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

Note that the ">" needs to be escaped within a [ ] construct.

-z 字符串为空,即长度为零

-z string is null, that is, has zero length

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

这篇关于为什么&quot; [1&gt; 2]";评估为True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆