David
David

Reputation: 3105

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?

Upvotes: 1

Views: 53

Answers (2)

glenn jackman
glenn jackman

Reputation: 246764

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

Upvotes: 2

Mr. Llama
Mr. Llama

Reputation: 20889

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.

Upvotes: 1

Related Questions