Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perform addition using a while or until loop??

Status
Not open for further replies.

Monunix

Instructor
Dec 4, 2003
3
SE
Hi,
I'm need to write a shell script that performs addition as much as the user requires using a while or an until loop but can only find "basic" addition script. Please help if you can.
Thanks/
 
What is 'basic' ?
((vara=$vara+99))
or
((vara=$vara + $varb)) ??

Post what you have and what you want in more detail.

Dickie Bird (:)-)))
 
Hi Dickiebird,
I work as an instructor for a telecom company and deliver a system administration course for a node based on a ufs and so this request came from one of my students. I don't do any scripting as part of the course - (it's mostly troubleshooting, backups & dumps )but have found a few basic calculating scripts in some unix text books but nothing with while or until...would I be right in assuming it's not a simple thing to do??
Thanks for your response anyway.
 
Nope - easy example :-

while :
do
print "Enter a number to add to total or 0 to quit \c"
read num
((total=$total + num))
if [ $num -eq 0 ]
then
exit
fi
print "\nRunning total is $total \n\n"
done

Dickie Bird (:)-)))
 
And here's another example if you have a bunch of files with numbers in them you want to add up and put the total in another file:

for filename in *.num
do
typeset -i i
i=0
while read -r j
do
i=i+j
done < ${filename}
echo $i > ${filename}.total
done
 
In the Korn shell, you can use the very C like...
Code:
    (( TOTAL += NUM ))
...for adding the number to the total. Note, you don't use the dollar sign. It's actually just using the variable name.

Hope this helps.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top