Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2011
    Posts
    6

    Unanswered: 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:

    HTML 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. #2
    Join Date
    Jan 2007
    Location
    Jena, Germany
    Posts
    2,721
    You are aware that your loop doesn't work because you assign the arguments to "x" but then you add $argement?

    Aside from a loop, you could also do something like this:
    Code:
    echo $* | sed -e 's/  */\+/g' | bc
    Knut Stolze
    IBM DB2 Analytics Accelerator
    IBM Germany Research & Development

  3. #3
    Join Date
    Oct 2011
    Posts
    6
    you are right I have to correct the x variable. But how can I make it run in a while loop that is my question

    thanks

  4. #4
    Join Date
    Sep 2009
    Location
    Ontario
    Posts
    1,057
    Provided Answers: 1
    Use the $# variable (the number of command line parameters)
    Code:
    num=$#
    while [ $num -gt 0 ]
    do
    blah blah
    num=`expr $num - 1`
    done
    or
    Code:
    while [ $1 -ne 0 ]
    do
    total=`expr $total + $1`
    shift
    done
    Make the last command line parameter zero.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •