Advanced Bash-Scripting Guide: A complete guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 12. External Filters, Programs and Commands | Next |
Decompose an integer into prime factors.
bash$ factor 27417 27417: 3 13 19 37 |
These are flexible, arbitrary precision calculation utilities.
bc has a syntax vaguely resembling C.
dc uses RPN ("Reverse Polish Notation").
Of the two, bc seems more useful in scripting. It is a fairly well-behaved UNIX utility, and may therefore be used in a pipe.
Bash can't handle floating point calculations, and it lacks operators for certain important mathematical functions. Fortunately, bc comes to the rescue.
Here is a simple template for using bc to calculate a script variable.
variable=$(echo "OPTIONS; OPERATIONS" | bc) |
Example 12-27. Monthly Payment on a Mortgage
1 #!/bin/bash 2 # monthlypmt.sh: Calculates monthly payment on a mortgage. 3 4 5 # This is a modification of code in the "mcalc" (mortgage calculator) package, 6 # by Jeff Schmidt and Mendel Cooper (yours truly, the author of this document). 7 # http://www.ibiblio.org/pub/Linux/apps/financial/mcalc-1.6.tar.gz [15k] 8 9 echo 10 echo "Given the principal, interest rate, and term of a mortgage," 11 echo "calculate the monthly payment." 12 13 bottom=1.0 14 15 echo 16 echo -n "Enter principal (no commas) " 17 read principal 18 echo -n "Enter interest rate (percent) " # If 12%, enter "12", not ".12". 19 read interest_r 20 echo -n "Enter term (months) " 21 read term 22 23 24 interest_r=$(echo "scale=9; $interest_r/100.0" | bc) # Convert to decimal. 25 # "scale" determines how many decimal places. 26 27 28 interest_rate=$(echo "scale=9; $interest_r/12 + 1.0" | bc) 29 30 31 top=$(echo "scale=9; $principal*$interest_rate^$term" | bc) 32 33 echo; echo "Please be patient. This may take a while." 34 35 let "months = $term - 1" 36 for ((x=$months; x > 0; x--)) 37 do 38 bot=$(echo "scale=9; $interest_rate^$x" | bc) 39 bottom=$(echo "scale=9; $bottom+$bot" | bc) 40 # bottom = $(($bottom + $bot")) 41 done 42 43 # let "payment = $top/$bottom" 44 payment=$(echo "scale=2; $top/$bottom" | bc) 45 # Use two decimal places for dollars and cents. 46 47 echo 48 echo "monthly payment = \$$payment" # Echo a dollar sign in front of amount. 49 echo 50 51 52 exit 0 53 54 # Exercises: 55 # 1) Filter input to permit commas in principal amount. 56 # 2) Filter input to permit interest to be entered as percent or decimal. 57 # 3) If you are really ambitious, 58 # expand this script to print complete amortization tables. |
Example 12-28. Base Conversion
1 : 2 ########################################################################## 3 # Shellscript: base.sh - print number to different bases (Bourne Shell) 4 # Author : Heiner Steven (heiner.steven@odn.de) 5 # Date : 07-03-95 6 # Category : Desktop 7 # $Id: base.sh,v 1.2 2000/02/06 19:55:35 heiner Exp $ 8 ########################################################################## 9 # Description 10 # 11 # Changes 12 # 21-03-95 stv fixed error occuring with 0xb as input (0.2) 13 ########################################################################## 14 15 # ==> Used in this document with the script author's permission. 16 # ==> Comments added by document author. 17 18 NOARGS=65 19 PN=`basename "$0"` # Program name 20 VER=`echo '$Revision: 1.2 $' | cut -d' ' -f2` # ==> VER=1.2 21 22 Usage () { 23 echo "$PN - print number to different bases, $VER (stv '95) 24 usage: $PN [number ...] 25 26 If no number is given, the numbers are read from standard input. 27 A number may be 28 binary (base 2) starting with 0b (i.e. 0b1100) 29 octal (base 8) starting with 0 (i.e. 014) 30 hexadecimal (base 16) starting with 0x (i.e. 0xc) 31 decimal otherwise (i.e. 12)" >&2 32 exit $NOARGS 33 } # ==> Function to print usage message. 34 35 Msg () { 36 for i # ==> in [list] missing. 37 do echo "$PN: $i" >&2 38 done 39 } 40 41 Fatal () { Msg "$@"; exit 66; } 42 43 PrintBases () { 44 # Determine base of the number 45 for i # ==> in [list] missing... 46 do # ==> so operates on command line arg(s). 47 case "$i" in 48 0b*) ibase=2;; # binary 49 0x*|[a-f]*|[A-F]*) ibase=16;; # hexadecimal 50 0*) ibase=8;; # octal 51 [1-9]*) ibase=10;; # decimal 52 *) 53 Msg "illegal number $i - ignored" 54 continue;; 55 esac 56 57 # Remove prefix, convert hex digits to uppercase (bc needs this) 58 number=`echo "$i" | sed -e 's:^0[bBxX]::' | tr '[a-f]' '[A-F]'` 59 # ==> Uses ":" as sed separator, rather than "/". 60 61 # Convert number to decimal 62 dec=`echo "ibase=$ibase; $number" | bc` # ==> 'bc' is calculator utility. 63 case "$dec" in 64 [0-9]*) ;; # number ok 65 *) continue;; # error: ignore 66 esac 67 68 # Print all conversions in one line. 69 # ==> 'here document' feeds command list to 'bc'. 70 echo `bc <<! 71 obase=16; "hex="; $dec 72 obase=10; "dec="; $dec 73 obase=8; "oct="; $dec 74 obase=2; "bin="; $dec 75 ! 76 ` | sed -e 's: : :g' 77 78 done 79 } 80 81 while [ $# -gt 0 ] 82 do 83 case "$1" in 84 --) shift; break;; 85 -h) Usage;; # ==> Help message. 86 -*) Usage;; 87 *) break;; # first number 88 esac # ==> More error checking for illegal input would be useful. 89 shift 90 done 91 92 if [ $# -gt 0 ] 93 then 94 PrintBases "$@" 95 else # read from stdin 96 while read line 97 do 98 PrintBases $line 99 done 100 fi |