# SHELL/BASH: Calculate Loan EMI Amount using script in Linux

In this article I will share a sample script to Calculate Loan EMI Amount using a shell script in Linux. While the formula to calculate payments based on the principal, interest rate, and duration of the loan is a bit tricky, some judicious use of shell variables can tame the mathematical beast and make it surprisingly understandable.

## Formula to Calculate Loan EMI Amount

The formula to calculate the EMI amount which we will use is as below

`M = P * ( J / (1 - (1 + J) ^ - N))`

Here, P is the principal or the amount that is borrowed as a loan J is the rate of interest that is levied on the loan amount (the interest rate should be a monthly rate) N is the duration of the loan in terms of months. So if you select a term of 5 years, n will be 60.

## Calculate Loan EMI - Shell Script

The below script expects another library file "scriptbc" to be present in your PATH variable.

Now below is our sample script to calculate loan EMI amount. You can modify it as per your requirement:

```# cat /tmp/loancalc.sh
#!/bin/bash

# loancalc--Given a principal loan amount, interest rate, and
#   duration of loan (years), calculates the per-payment amount

nicenumber()
{
# Note that we assume that '.' is the decimal separator in the INPUT value
#   to this script. The decimal separator in the output value is '.' unless
#   specified by the user with the -d flag.

integer=\$(echo \$1 | cut -d. -f1)        # Left of the decimal
decimal=\$(echo \$1 | cut -d. -f2)        # Right of the decimal
# Check if number has more than the integer part.
if [ "\$decimal" != "\$1" ]; then
# There's a fractional part, so let's include it.
result="\${DD:= '.'}\$decimal"
fi

thousands=\$integer

while [ \$thousands -gt 999 ]; do
remainder=\$((\$thousands % 1000))    # Three least significant digits

# We need 'remainder' to be three digits. Do we need to add zeros?
while [ \${#remainder} -lt 3 ] ; do  # Force leading zeros
remainder="0\$remainder"
done

result="\${TD:=","}\${remainder}\${result}"    # Builds right to left
thousands=\$((\$thousands / 1000))    # To left of remainder, if any
done

nicenum="\${thousands}\${result}"
if [ ! -z \$2 ] ; then
echo \$nicenum
fi
}

if [ \$# -ne 3 ] ; then
echo "Usage: \$0 principal interest loan-duration-years" >&2
exit 1
fi

P=\$1 I=\$2 L=\$3
J="\$(scriptbc -p 8 \$I / \( 12 \* 100 \) )"
N="\$(( \$L * 12 ))"
M="\$(scriptbc -p 8 \$P \* \( \$J / \(1 - \(1 + \$J\) \^ -\$N\) \) )"

# Now a little prettying up of the value:
amount="\$(echo \$M | cut -d. -f1)"
cents="\$(echo \$M | cut -d. -f2 | cut -c1-2)"

cat << EOF
A \$L-year loan at \$I% interest with a principal amount of \$(nicenumber \$P 1 )
results in a payment of Rs \$amount.\$cents each month for the duration of
the loan (\$N payments).
EOF

exit 0```

## How It Works

Exploring the formula itself is beyond the scope of this article, but it’s worth noting how a complex mathematical formula can be implemented directly in a shell script. The entire calculation could be solved using a single long input stream to `bc`, because that program also supports variables. However, being able to manipulate the intermediate values within the script itself proves beyond the capabilities of the `bc` command alone. Also, frankly, breaking up the equation into a number of intermediate equations also facilitates debugging. For example, here’s the code that splits the computed monthly payment into amount and cents and ensures that it’s presented as a properly formatted monetary value:

```amount="\$(echo \$M | cut -d. -f1)"
cents="\$(echo \$M | cut -d. -f2 | cut -c1-2)"```

The `cut` command proves useful here. The second line of this code grabs the portion of the monthly payment value that follows the decimal point and then chops off anything after the second character. If you would prefer to round this number to the next nearest cent instead, just add `0.005` to the value before truncating the cents at two digits.

## Running the Shell Script

This minimalist script expects three parameters: the amount of the loan, the interest rate, and the duration of the loan (in years). Now assuming I am planning to take a loan of 36 lakh where the rate of interest would be 8.65% and the loan period would be 20 years

```[root@node1 ~]# /tmp/loancalc.sh 3600000 8.65 20
A 20-year loan at 8.65% interest with a principal amount of 3,600,000
results in a payment of Rs 31584.24 each month for the duration of
the loan (240 payments).```

So as per our script the EMI which we have to pay per month would be 31584.24. Now this amount can be dollar or rupees or any currency which you follow. You do not need to do any currency conversion here as the script would be generic to calculate loan EMI. For this article I have Rupees as the preferred currency.   For the same loan amount and rate of interest for a period of 30 years, the EMI value would be Rs 28064.44 per month

```[root@node1 ~]# /tmp/loancalc.sh 3600000 8.65 30
A 30-year loan at 8.65% interest with a principal amount of 3,600,000
results in a payment of Rs 28064.44 each month for the duration of
the loan (360 payments).```

Lastly I hope the steps from the article to calculate loan EMI using shell script on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

References:
Wicked Cool Scripts