简体   繁体   中英

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

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

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.

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

Here's some details on comparison operators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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