简体   繁体   English

Shell打印编号小于第一个编号

[英]Shell print numbers that are smaller than first number

I'm trying to print the numbers that are smaller than first number 我正在尝试打印小于第一个数字的数字

./8d 100 5 8 6

so my result should be 5 8 6 所以我的结果应该是5 8 6

 #!/bin/bash
    for i in $*
    do
    if [[ $1 > $i ]]; then
        echo "Num " $i
    fi
    done

But I dont get any result. 但我没有得到任何结果。 What I'm doing wrong? 我做错了什么?

The problem with your code is that it's doing lexical comparisons, not numerical. 您的代码的问题在于它正在进行词法比较,而不是数字。 10 and 1 are both smaller than 100 lexically, but the numbers you supplied are larger. 101都小于100词法,但你提供的数字更大。

I'd code that like this, I think it's clearer 我的代码是这样的,我认为它更清楚

#!/bin/bash
base=$1
shift
for n do 
    (( base > n )) && echo $n 
done

and

$ smaller 100 5 8 1234 6 100
5
8
6

You should be using -lt / -eq / -gt to compare integers. 您应该使用-lt / -eq / -gt来比较整数。

if [[ $1 -gt $i ]]; then
    echo "Num " $i
fi

Here's some details on comparison operators. 以下是比较运算符的一些细节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM