Marko
Marko

Reputation: 417

How does while take parametral conditions?

I have a simple code:

compare()
{
        n=$#
        echo "Refference number: "
        read x

        while [ $n -gt 0 ]
                do
                if [ $1 -gt $x ]
                        then
                        echo "A greater number was found: " $1
                fi
                shift
        done
}

In this manner the script doesnt work well. I get an infinite loop with error on the while line.

If I replace that while line with while [ $# -gt 0 ] everything works fine.

Why is this happening? Isnt $n=$# ? I use CentOS 7.

Upvotes: 0

Views: 258

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754820

$n contains a copy of the value of $# at the time it was assigned. Nothing changes $n thereafter, so the loop either runs not at all or runs continuously.

When you use $# in the loop condition, the shift reduces the number of arguments by one, and therefore $# decreases, and the loop terminates.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 362007

You can use $# directly in the while loop. It will naturally change each time you call shift.

while [ $# -gt 0 ]; do
    ...
    shift
done

Otherwise, you'll have to update $n yourself each iteration.

while [ "$n" -gt 0 ]; do
    ...
    shift
    ((--n))
done

Assigning n=$# makes $n equal to $# at that point in time. It doesn't mean it is automatically updated when $# changes.

Upvotes: 3

Related Questions