Bash Project: Score Report
A score report script reads results from a file and prints a summary. It combines file reading, a loop, arithmetic, and a condition in one program.
Read names and scores
Each line of the file holds a name and a score. The read command stores them in two separate variables.
echo "Ana 80" > scores.txt
echo "Ben 90" >> scores.txt
while read name score; do
echo "$name scored $score"
done < scores.txtCount and add in the loop
The loop adds one to the count on every line. It also adds each score into the running total.
echo "Ana 80" > scores.txt
echo "Ben 90" >> scores.txt
echo "Cara 70" >> scores.txt
count=0
total=0
while read name score; do
count=$((count + 1))
total=$((total + score))
done < scores.txt
echo "Count: $count"
echo "Total: $total"Track the top score
An if test compares each score with the best score so far. A higher score replaces both the top score and the top name.
echo "Ana 80" > scores.txt
echo "Ben 90" >> scores.txt
echo "Cara 70" >> scores.txt
top=0
topname=""
while read name score; do
if [ "$score" -gt "$top" ]; then
top=$score
topname=$name
fi
done < scores.txt
echo "Top: $topname with $top"Example
echo "Ana 80" > scores.txt
echo "Ben 90" >> scores.txt
echo "Cara 70" >> scores.txt
echo "Dan 100" >> scores.txt
count=0
total=0
top=0
topname=""
while read name score; do
count=$((count + 1))
total=$((total + score))
if [ "$score" -gt "$top" ]; then
top=$score
topname=$name
fi
done < scores.txt
average=$((total / count))
echo "Students: $count"
echo "Total: $total"
echo "Average: $average"
echo "Top scorer: $topname with $top"Key points
- A while read loop reads a file one line at a time.
- The read command can store two fields in two variables.
- A counter adds one for each line the loop processes.
- The $(( )) form adds each score into a running total.
- Integer division of the total by the count gives the average.
- An if test inside the loop can track the highest score seen.
In this example, one loop counts the students, totals the scores, and tracks the top score. The average is 340 divided by 4, which is exactly 85. Dan has the highest score, with 100.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How does the script compute the average score?