Calculate Your GPA Using this Bash Script
This Bash script is used to calculate your Grade Point Average (GPA) on the command line. Usage might not be intuitive. Please see the usage function or just run the script without passing it any arguments.
The gval function should be edited to reflect your own region or university. It has been written and tested on Bash 3.2.48.
#!/bin/sh
#
# Bash GPA calculator
#
# Isam | r0cketjump@yahoo.com | biodegradablegeek.com
# 05/21/2009 - Just another 4 AM project
function usage {
echo -e "\nBASH GPA Calculator"
echo
echo -e "\tAccepts an even # of arguments in the form of C G C G C G ..."
echo -e "\t (C = number of credits, G = grade for the course)"
echo
echo -e "\tExample: You got a B+ in a 4 credit course, "
echo -e "\t an A in a 3 credit course, etc.."
echo
echo -e "\tUSAGE: $0 4 B+ 3 A 3 F 3 B-"
echo
echo "Acceptable grades are A B C D F WU (eq to F)"
echo
}
function calc {
echo `echo "scale=3; $1" | bc`
}
function gval {
grade=`echo "$1" | tr [a-z] [A-Z]`
case $grade in
A+ ) echo '4.3';;
A ) echo '4';;
A- ) echo '3.7';;
B+ ) echo '3.3';;
B ) echo '3.00';;
B- ) echo '2.7';;
C+ ) echo '2.3';;
C ) echo '2.0';;
C- ) echo '1.7';;
D+ ) echo '1.3';;
D ) echo '1.0';;
D- ) echo '0.7';;
F ) echo '0';;
WF ) echo '0';;
WU ) echo '0';;
esac
}
# check # of arguments. is it even?
let MOD=$#%2
if [ ! $MOD -eq 0 ]; then
usage
exit
elif [ $# -eq 0 ]; then
usage
exit
fi
args=($@)
n=${#args[@]}
points=0
credits=0
for ((i=0;i<$n-1;i+=2)); do
k=${i}
creds=${args[$k]}
cgrade=${args[$k+1]}
# convert cgrade (C-) to a number
grade=`gval $cgrade`
pts=`calc $grade*$creds`
echo "$creds * $cgrade ($grade) = $pts"
points=`calc $points+$pts`
credits=`calc $credits+$creds`
done
gpa=`calc $points/$credits`
echo "------------"
echo "Total points = $points"
echo "Total credits = $credits"
echo "------------"
echo "** GPA (pts/crd) = $gpa"
echo "------------"
(Script uses bc as the calculator. Change that in the calc function if you need to.)
I’ll never get used to Bash’s ugly ass syntax. … esac?
Why not subscribe to the feed?. If you’re on a mobile device I suggest Viigo
Tags: bash, code, Code example, scripting, Scripts
Leave a Reply