while loop problem - Unix

This is a discussion on while loop problem - Unix ; Hello everyone, I have this little for loop that I want to convert to a while loop. It accepts unknown number from the command line parameters and then add them all up and display the sum, here is the for ...

+ Reply to Thread
Results 1 to 2 of 2

Thread: while loop problem

  1. while loop problem

    Hello everyone,

    I have this little for loop that I want to convert to a while loop. It accepts unknown number from the command line parameters and then add them all up and display the sum, here is the for loop:

    Code:
    sum=0
    
    for x in $*
    do 
    sum=`expr $sum + $argument`
    done
    
    echo $sum
    it runs perfectly, any suggestions how to convert it to a while loop?

    Thank you

    Regards

  2. Re: while loop problem

    How about the following:
    Code:
    sum=0
    x=0
    args=($*)
    
    while [[ $x -le ${#*}-1 ]]
    do
       sum=`expr $sum + ${args[$x]}`
       let x++
    done
    
    echo $sum
    We need to do a "-1" otherwise it throws a syntax error.

    args equals "0-4" (total 5) but we are doing `${#*}` which equals "5"

    With the above logic 0 < 5 ... 4 < 5, 5 <= 5 total of 6 statements. The while loop doesn't like that, but if we do `x=1` then we exclude "1" which is in the "0" position of the array we created in args.

    Hopefully I didn't confuse anyone to much.
    Last edited by monsi; 11-11-2011 at 04:40 AM.

+ Reply to Thread