Free Hosting Online for WorkStations

< Previous | Contents | Next >

An Example Script

As a real-world example, we will construct a script that performs a common calculation, monthly loan payments. In the script below, we use a here document to pass a script to bc:


#!/bin/bash

# loan-calc: script to calculate monthly loan payments PROGNAME=${0##*/} # Use parameter expansion to get basename usage () {

cat <<- EOF

Usage: $PROGNAME PRINCIPAL INTEREST MONTHS


Where:


PRINCIPAL is the amount of the loan. INTEREST is the APR as a number (7% = 0.07). MONTHS is the length of the loan's term.


EOF

}


if (($# != 3)); then usage

exit 1

fi


principal=$1 interest=$2 months=$3


bc <<- EOF

scale = 10

i = $interest / 12 p = $principal

n = $months

a = p * ((i * ((1 + i) ^ n)) / (((1 + i) ^ n) - 1)) print a, "\n"

EOF

#!/bin/bash

# loan-calc: script to calculate monthly loan payments PROGNAME=${0##*/} # Use parameter expansion to get basename usage () {

cat <<- EOF

Usage: $PROGNAME PRINCIPAL INTEREST MONTHS


Where:


PRINCIPAL is the amount of the loan. INTEREST is the APR as a number (7% = 0.07). MONTHS is the length of the loan's term.


EOF

}


if (($# != 3)); then usage

exit 1

fi


principal=$1 interest=$2 months=$3


bc <<- EOF

scale = 10

i = $interest / 12 p = $principal

n = $months

a = p * ((i * ((1 + i) ^ n)) / (((1 + i) ^ n) - 1)) print a, "\n"

EOF


When executed, the results look like this:



[me@linuxbox ~]$ loan-calc 135000 0.0775 180

[me@linuxbox ~]$ loan-calc 135000 0.0775 180


1270.7222490000

1270.7222490000


This example calculates the monthly payment for a $135,000 loan at 7.75% APR for 180 months (15 years). Notice the precision of the answer. This is determined by the value given to the special scale variable in the bc script. A full description of the bc script- ing language is provided by the bc man page. While its mathematical notation is slightly different from that of the shell (bc more closely resembles C), most of it will be quite fa- miliar, based on what we have learned so far.


Top OS Cloud Computing at OnWorks: