LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Begginers problem - arbitary numbers (https://www.linuxquestions.org/questions/linux-newbie-8/begginers-problem-arbitary-numbers-383649/)

JacksWastedLife 11-16-2005 08:27 AM

Begginers problem - arbitary numbers
 
Howdy. :) I am very new to Linux and am having some some difficulty with a paritcular problem. I am trying to write a script that reads in ten arbitary numbers and prints to the screen the sum of these numbers. Anyone have any ideas how I would go about doing this?

gnu2tux 11-16-2005 08:45 AM

Haven't tried it but I guess (assuming the arbitary number is a random number from /dev/random) then:

#!/bin/bash

until [ $i -eq 10 ]

do
$i = /dev/random
$sum = $sum + $i
done

echo "The total is: $sum"

if you get an error, its probably my syntax is wonky with the brackets, have a quick squint at the bash/while/until manpage or the likes or on google to debug.

Cheers,

Ali Ross

Y0jiMb0 11-16-2005 08:54 AM

Code:

#!/bin/bash

until [ $i -eq 10 ]

do
$i = /dev/random
$sum = $sum + $i
done

echo "The total is: $sum"

This is slightly wrong; you must remove the $ at left hand sides, and beware the spaces in bash scripts, they have to be used when they have to, no more no less.
Moreover, you should initialize the variables, for safety.
This should work:
Code:

#!/bin/bash

sum=0
for j in 0 1 2 3 4 5 6 7 8 9
do
i=$RANDOM
sum=$[sum+i]
done
echo "The total is: $sum"

If you want to read in the numbers from command line (interactively) use the read command ("man read" for more help):
instead of
Code:

i=$RANDOM
use
Code:

read i
Regards


All times are GMT -5. The time now is 04:42 PM.