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:
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?
I'll give you a hint. You use a while loop so that the loop occurs while some condition is satisfied. Now, what is the condition that must be satisfied for this while loop to keep running? It is that the user enters a number, right?
the user enters all the parameters at once. in this for loop all of the parameters is stored in the $* variable so it is easy for the loop to go through all of them, but i cannot understand how to do it in a while loop.
I'm way too rusty and forgetful to give any more than a possible hint. Isn't there a variable that tells the number of parameters that were specified? Or something that flags the last one?
OK. Your total number of arguments is given by $#. So you can set up a counter starting at 1 and increment that counter until it is greater than the number of arguments. You convert the counter value into the name of the argument you want to look at, and you'll have it.
Take a look at how parameter expansions work. Pay attention to the discussion of indirection.
There is also an obscure brace expansion syntax that allows you to start at a specified point in an array and proceed for a specified number of elements. This works as well as a parameter expansion but you'll have a much harder time finding any information about it.
You can avoid the counter if you wish by looking at each command line variable, after you've obtained it by the appropriate expansion, and continue until you find an empty string for the variable.
Been a very long time since I have done bash scripting but I would assume you could do something like this. Can't remember all the syntax.
Code:
While [ -n $1 ]
do
sum=`expr $sum + $1`
shift
done
Status
Not open for further replies.
You have insufficient privileges to reply here.
Related Threads
?
?
?
?
?
Tech Support Guy
9.9M posts
860K members
Since 1998
A forum community dedicated to tech experts and enthusiasts. Come join the discussion about articles, computer security, Mac, Microsoft, Linux, hardware, networking, gaming, reviews, accessories, and more!