April 3rd, 2008 at 12:06 pm

Calculate interest rates with a shell script

If you put your cash to a bank account, you will want to know how much money you get with a certain amount at a given rate within a given period. Save the following Bash script as /usr/local/bin/loancalc (or something like that), make it executable, and you will be able to calculate the return on your investments with a single one-liner.

#!/bin/bash
 
function calc()
{
	return $(echo "scale=$2; $1" | bc)
}
 
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
	echo "$0 calculates the interest loan of a given amount with a given rate for a given duration."
	echo "Usage: $0 AMOUNT RATE DURATION"
	exit 0
fi
 
if [ -z "$3" ]; then
	echo "Please enter the amount, the rate and the duration (in this order)."
	exit 1
fi
 
AMOUNT=$1
ZINS=$2
DURATION=$3
 
echo "Investment: $AMOUNT bucks at a rate of $ZINS% for $DURATION years."
echo "          Loan            Total"
 
for i in $(seq 1 $DURATION); do
	INTERESTLOAN=$(echo "scale=10; ($AMOUNT/100)*$ZINS" | bc)
	AMOUNT=$(echo "scale=10; $AMOUNT+$INTERESTLOAN" | bc)
	printf "Year ${i} %8.2f " $INTERESTLOAN; printf " %14.2f\n" $AMOUNT;
done
 
printf "Final amount: %1.2f bucks.\n" $AMOUNT

For example:

you@yourmachine ~ $ loancalc 3000 3.5 5
Investment: 3000 bucks at a rate of 3.5% for 5 years.
          Loan            Total
Year 1   105.00         3105.00
Year 2   108.68         3213.68
Year 3   112.48         3326.15
Year 4   116.42         3442.57
Year 5   120.49         3563.06
Final amount: 3563.06 bucks.

Leave a Comment