Find the answer to your Linux question:
Results 1 to 4 of 4
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #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:

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

    Thank you


  2. #2
    If it works, why does it need to be converted to a while loop?

  3. #3
    because it is one of the requirements. I have to do it in both (while and for) loops.


  4. $spacer_open
  5. #4
    You can run a while loop by testing for the number of command line arguments (positional parameters) passed to your script. In your while loop, just shift after you do your sum command, so that:

    a) you're always using the first positional parameter in your sum calculation

    b) the positional parameter count will eventually get to zero (ending your while logic)

    Do 'man bash' to read up on these functions.

Posting Permissions

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