Originally published October 13, 2016 @ 12:48 am

Just a little bit of fun with Bash: a loan payment calculator. Nothing fancy here. Maybe I’ll add the amortization schedule to it later…

#!/bin/bash
principal=$(echo  | sed -r 's/[,]//g')
apr=
life=

d() {
	sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'
}

if [ -z "${principal}" ] || [ -z "${apr}" ] || [ -z "${life}" ]
then
	exit 1
fi

apr="$(echo "scale=6; ${apr} / (100*12)" | bc -q)"
payments=$(( ${life} * 12 )) 
c="${principal} * ( ${apr} * ((1 + ${apr}) ^ ${payments} )) / ( ((1 + ${apr}) ^ ${payments}) - 1)"
payment="$(echo "scale=2; $${c}" | bc -q)"
interest="$(echo "scale=2; ${payment} * ${payments} - ${principal}" | bc -q)"
echo "You'll be making ${payments} monthly payments of $`echo ${payment} | d` to pay off $`echo ${principal} | d` at %, paying $`echo ${interest} | d` in interest"

Sample run:

(root:brocksamson)-(bg:0)-(~)# loancalc 30,000.00 4.75 5
You'll be making 60 monthly payments of $562.63 to pay off $30,000.00 at 4.75%, paying $3,757.80 in interest