Running Total Running Wild

Hi. A shell scripting newbie here. I am trying to write a script that will create a running total of Sales, and increment a counter for each Sales entry, but when I executed the program it never stopped.

counter=0
Sales=0
echo "enter sales price"
read sales
while [ "$sales" != "" ]
do
let counter=counter+1
let total=total+sales
echo $counter
echo $total
done

I'd appreciate any help to get this script straightened out.
TIA

Try putting these two lines inside the while loop:

echo "enter sales price"
read sales

Thank you that did it.

Now my next problem. I enter a number, but the script is not totaling. It just outputs the number that I entered.

What did I leave out?
TIA

You have to use $total, $count on the right side of the '=' so that the value of those variables are used.

e.g total=$total + $sales

I tried this, with no luck.

let counter=$counter+1
let total=$total+$sales

Make sure that there is no extra space in the expression:


  let count=$count+1

not

  let count=$count + 1

What is the error msg that you are getting? Also, define 'sales' not 'Sales'.

It seems to work on my system. I'm using ksh.

Taking into account the earlier postings and error messages you will have seen during testing, by now your shell script should look something vaguely like this example:

#!/bin/ksh
counter=0
sales=0
total=0
while [ "$sales""X" != "X" ]
do
     echo "Enter sales price: \c" ; read sales
     let counter=$counter+1
     let total=$total+$sales
     echo "Counter : $counter"
     echo "Running total: $total"
done

The first line (the shebang line) states which shell we are using.

Indentation adds to readability.

We have appended an arbitary character "X" to "$sales" in the while statement to avoid the syntax error when we finally don't enter a value and want to exit the loop. (There are other ways of achieving the same effect).

For completeness and readablility we initialise $total .

We can extend the "echo" statements to improve the layout on the screen and to provide more information about what the output means. The "\c" in the first echo stops echo outputting a newline character such that the user enters the answer on the same line as the question.