Register
It is currently Fri Apr 25, 2014 3:23 am

I need some help with a simple for loop


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Thu May 08, 2008 3:36 am   

Joined: Thu May 08, 2008 3:23 am
Posts: 4
Well I just recently dived head first into Linux and I am trying to learn as much as I can about every aspect. So I have been reading a lot about scripting and I am interested in learning more about how to create them. I am reading a guide online and it just challenged me to write a script that sums the numbers passed to the script as arguments on the command line, using the for loop and displays the results. So I have to warn you I am very new to this but this is what I got so far, as you can see the script is not going to well. Any help would be appreciated!

#!/bin/bash
#
echo
echo -n "Sum for: "
echo "number: $number"
for number in "$@"
do
expr $number + $number + $number
echo "number: $number"
done
echo

I am trying to sum for three numbers as arguments then display the numbers and what they added up to at the end of the script.
example
$Sum for 10 20 30
10+20+30=60


Top
 Profile  
 PostPosted: Thu May 08, 2008 10:18 am   
User avatar

Joined: Sun Apr 13, 2008 4:05 am
Posts: 37
Location: /dev/random
try this
Code:
#!/bin/bash
#

echo -n "Sum for: "
read input
for number in `echo $input | sed s/\ /'\n'/g`
do
echo -n $number  " + "
var=`expr $var + $number`
done
echo -n " = " $var


Top
 Profile  
 PostPosted: Fri May 09, 2008 2:13 pm   

Joined: Thu May 08, 2008 3:23 am
Posts: 4
I think that script remembers the last total that was calculated then adds it to the script every time I run it. So the first time I run the script 10+20+30=60 but when I run it again 10+20+30=120

How easy would it be to turn this script into a while or untill loop? Would I have to change very much?

I guess I still have some more learning to do...thanx for the help!!


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP