LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   shell programming (https://www.linuxquestions.org/questions/linux-newbie-8/shell-programming-380561/)

qerf 11-06-2005 03:41 PM

shell programming
 
i have to calculate mean value using shell programming.
ex:
./mean 11 15 18 19 41 45
but i cant succeed the getting arguments. The problem is count of arguments. I search web and see examples they are doing like that
n1=$1
n2=$2
n3=$3
...
..
but in my situation, number of arguments is unknown i mean, there will be only two or one hundred arguments. how cant i get arguments in this situation?
show me the rigth way thnx...

TBC Cosmo 11-06-2005 04:38 PM

Try using shift, described here

Andrew Benton 11-06-2005 04:48 PM

Code:

#!/bin/bash
for i in $*
do total=$(($total+$i))
echo $total
done
echo $(($total/$#))


Mad Scientist 11-06-2005 04:51 PM

Here's something that will work.

Code:

#!/bin/bash
# Compute the average of the numbers in file 'input'

SUM=0
NUM=0

for i in `sed -n p input`
do
let "SUM=$SUM+$i"
let "NUM=$NUM+1"
done

let "AVG=$SUM/$NUM"

echo $AVG

exit 0

You can name this file "avg". Then, place all the numbers you want to average in a file called "input", but make sure that there is only one number appearing on each line. For example, you could have a file "input" with the contents

Code:

1
2
3
4
5

And if you named your script "avg", and in the same directory you have the file "input" with the above contents, then from this directory can type

Code:

sh avg
and the number 3 should be printed to the terminal.

Mad Scientist 11-06-2005 04:54 PM

Whoops, Andrew got his in a few minutes before mine, and I didn't see it. His is simpler, and takes input more in the way you were asking for them.

Andrew Benton 11-06-2005 05:28 PM

Yes, but it doesn't do decimals, I had to use bc for that
Code:

#!/bin/bash
total=0
for i in $*
do
total=$(echo "scale=3; $total+$i" | bc)
done
echo "average="$(echo "scale=3; $total/$#" | bc)



All times are GMT -5. The time now is 07:37 AM.