Wednesday, February 16, 2011

Displaying Decimal Number in Shell Scripts

Have you ever wanted to display a decimal number on your shell scripts? Bash by default is not able to display any decimal number and only plays well with integers.

There's a solution for this, which is by using bc, a simple calculator which is mostly provided in any Linux distributions. Let's play a bit with bc.

In order to display a decimal number using bc, you will have to define a scale variable. Please have a look on bc's manual page for detail. Use this command on your terminal to try it: echo "scale=4; 3/4" | bc -l. It will give you an output of .7500

Here's a simple script for a demo:
#!/bin/bash

SCORE=0
AVERAGE=0
SUM=0
NUM=0

while true; do
echo -n "Enter your score [0-100] ('q' for quit): ";
read SCORE;
if (("$SCORE" < "0")) || (("$SCORE" > "100")); then
echo "Be serious. Come'on, try again: "
elif [ "$SCORE" == "q" ]; then
echo -e "Average rating: \c"
result=`echo "scale=4; $SUM/$NUM" | bc -l`
echo "$result"
break
else
SUM=$[$SUM + $SCORE]
NUM=$[$NUM + 1]
fi
done

Try running it:
./average.sh
Enter your score [0-100] ('q' for quit): 1
Enter your score [0-100] ('q' for quit): 5
Enter your score [0-100] ('q' for quit): 4
Enter your score [0-100] ('q' for quit): q
Average rating: 3.3333

No comments:

Post a Comment