If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Data Access, Manipulation & Batch Languages > Unix Shell Scripts > while loop problem

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 11-09-11, 03:17
pfm200586 pfm200586 is offline
Registered User
 
Join Date: Oct 2011
Posts: 6
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
Reply With Quote
  #2 (permalink)  
Old 11-09-11, 12:30
stolze stolze is offline
Registered User
 
Join Date: Jan 2007
Location: Jena, Germany
Posts: 2,662
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
Reply With Quote
  #3 (permalink)  
Old 11-09-11, 13:05
pfm200586 pfm200586 is offline
Registered User
 
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
Reply With Quote
  #4 (permalink)  
Old 11-09-11, 13:13
kitaman kitaman is offline
Papabi's friend
 
Join Date: Sep 2009
Location: Ontario
Posts: 629
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.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On