27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

12.8. Math Commands<br />

"Doing the numbers"<br />

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

factor<br />

Decompose an integer into prime factors.<br />

bash$ factor 27417<br />

27417: 3 13 19 37<br />

bc<br />

Bash can't handle floating point calculations, and it lacks operators for certain important mathematical<br />

functions. Fortunately, bc comes to the rescue.<br />

Not just a versatile, arbitrary precision calculation utility, bc offers many of the facilities of a<br />

programming language.<br />

bc has a syntax vaguely resembling C.<br />

Since it is a fairly well−behaved UNIX utility, and may therefore be used in a pipe, bc comes in<br />

handy in scripts.<br />

Here is a simple template for using bc to calculate a script variable. This uses command substitution.<br />

variable=$(echo "OPTIONS; OPERATIONS" | bc)<br />

Example 12−32. Monthly Payment on a Mortgage<br />

#!/bin/bash<br />

# monthlypmt.sh: Calculates monthly payment on a mortgage.<br />

# This is a modification of code in the "mcalc" (mortgage calculator) package,<br />

# by Jeff Schmidt and Mendel Cooper (yours truly, the author of this document).<br />

# http://www.ibiblio.org/pub/Linux/apps/financial/mcalc−1.6.tar.gz [15k]<br />

echo<br />

echo "Given the principal, interest rate, and term of a mortgage,"<br />

echo "calculate the monthly payment."<br />

bottom=1.0<br />

echo<br />

echo −n "Enter principal (no commas) "<br />

read principal<br />

echo −n "Enter interest rate (percent) " # If 12%, enter "12", not ".12".<br />

read interest_r<br />

echo −n "Enter term (months) "<br />

read term<br />

interest_r=$(echo "scale=9; $interest_r/100.0" | bc) # Convert to decimal.<br />

# "scale" determines how many decimal places.<br />

Chapter 12. External Filters, Programs and Commands 196

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!