Bash math bc



bash math calculations using bc http://www.basicallytech.com/blog/?/archives/23-command-line-calculations-using-bc.html

addition

$ echo '57+43' | bc

100

subtraction

$ echo '57-43' | bc

14 multiplication

$ echo '57*43' | bc

2451

scale

The scale variable determines the number of digits which follow the decimal point

division

$ echo 'scale=25;57/43' | bc

1.3255813953488372093023255

square root

$ echo 'scale=30;sqrt(2)' | bc

1.414213562373095048801688724209

power

$ echo '6^6' | bc

46656

parentheses

$ echo '(6^6)^6' | bc $ echo '6^(6^6)' | bc

$ echo '7+(6*5)' | bc $ echo '(7+6)*5' | bc

obase and ibase

obase and ibase are special variables which define output and input base.

Legitimate obase values range from 2 to 999, although anything beyond 16 is wasted on me!

Legitimate ibase values range from 2 to 16.

convert from decimal to hexadecimal Here we're converting 255 from base 10 to base 16:

$ echo 'obase=16;255' | bc

FF

convert from decimal to binary And here we're converting the number 12 from base 10 to base 2:

$ echo 'obase=2;12' | bc

1100

convert from binary to decimal

Here we're converting the binary number 10 to a base 10 (decimal) number.

$ echo 'ibase=2;obase=A;10' | bc

2

convert from hexadecimal to decimal

$ echo 'ibase=16;obase=A;FF' | bc

255

using bc with shell scripts

$ FIVE=5 ; echo "$FIVE^2" | bc

25

Use of double-quotes to preserve the value of the variable $FIVE.