Results 1 to 4 of 4
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 ...
- 11-09-2011 #1Just Joined!
- Join Date
- Oct 2011
- Posts
- 4
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:
it runs perfectly, any suggestions how to convert it to a while loop?HTML Code:sum=0 for x in $* do sum=`expr $sum + $argument` done echo $sum
Thank you
Regards
- 11-09-2011 #2Linux Guru
- Join Date
- May 2011
- Posts
- 1,843
If it works, why does it need to be converted to a while loop?
- 11-09-2011 #3Just Joined!
- Join Date
- Oct 2011
- Posts
- 4
because it is one of the requirements. I have to do it in both (while and for) loops.
thanks
- 11-09-2011 #4Linux Guru
- Join Date
- May 2011
- Posts
- 1,843
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.


Reply With Quote