Please enable JavaScript eh!

 ⌘ Web Mechanic ⌘ 

Bash Scripting


bc

As mentioned in the Mathematics page, bash only understands integers when doing mathematics. bc is required for anything requiring decimals.

It should be available on MacOS and *nix computers. On my M4 it is in /usr/bin/bc - you may have to provide a full path to that directory or add it to your $PATH environment variable:

PATH=$PATH":/usr/bin/bc"

'bc' is actually considered a decimal arithmetic language - almost like regex.

The range of options available is large and somewhat daunting, but fear not - we don't need to understand ALL of them to be useful.

Possibly the most common option is -S - standing for scale, or how many significant decimals to use.

echo 'sqrt(13)' | bc -S4
3.6055

echo 'sqrt(17)' | bc -S4
4.1231

 echo 'sqrt(23)' | bc -S4
4.7958

echo '17^2' | bc -S4
289

echo '23^2' | bc -S4
529

echo 'sqrt((23^2) + (17^2))' | bc -S4
28.6006

It is used either as an interactive command; in a pipeline; or the recipient of a redirected file containing expressions. Here is a simple Pythagorean case:

Interactive

bc
>>> scale=4
>>> sqrt((17^2)+(23^2))
28.6006
>>> quit

After entering 'bc' at a shell prompt, we see the bc prompt '>>>'. Here we specified a 'scale'. Next we entered the 'formula' to solve the expression. There are numerous commands available in bc, but we only 2 for this:
'sqrt' and ^ for exponentiation.

While this is useful, what we really want is to be able do this in a script.

Scriptable

Here's an example script:

#!/bin/bash
# calculate 10 compounded values
start=912.52 # beginning value
inc=1.021 # increase per year (2.1%)
for ((i=1;i<=10;i++))
do
	R=$(echo "scale=12;$start*$inc" | bc)
	start=$(echo "scale=12;$R" | bc)
	printf "%.2f\n" $echo $R | bc -l
done

compound.sh
931.68
951.25
971.22
991.62
1012.44
1033.70
1055.41
1077.57
1100.20
1123.31

Note for 'R' we have 2 statements being passed to 'bc'. Both enclosed in double-quotes, and separated by a semi-colon.

We specified a 'scale' of 12 to get more precision, and then used the printf command to specify the number of decimals. The '-l' option for bc sets the default scale to 20, providing higher precision, before 'printf' displays the result.

Redirected

If we put our Pythagorean algorithm into a file (pyth.txt), we can use it like this:

bc < pyth.txt

pyth.txt contains:

scale=5
a=17
b=23
sqrt((a^2) + (b^2))
quit
It is important to include the 'quit' command

Shows us:

28.60069

Pipeline

When you're in a Terminal window you can quickly get some complex results easily.

echo "scale=8; sqrt(2)" | bc
1.41421356

I'm sure you can come up with more complex tasks, but this shows you the format you need. Essentially the same as scripting, but less typing.

For more details visit IEEE OpenGroup or 'man bc' on your computer.