Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Doing Calculations on the Command Line with the bc Tool and Your Shell

doing-calculations-on-the-command-line-with-the-bc-tool-and-your-shell.jpg

Here's how you can add, subtract, multiply and divide numbers without leaving your terminal.

Quick Jump:

Once in a while you may find yourself wanting to do a quick calculation on the command line or within a shell script. I typically reach for the bc tool for this but your shell also has a few ways to do basic calculations.

# Shell Script

Here’s a couple of examples using $(( ... )) which is POSIX compliant, you can use let or expr too but they tend to be less portable:

$ echo $(( 2 + 2 ))
4

$ echo $(( 3 * 3 ))
9

$ echo $(( 4 % 3 ))
1

$ value=$(( 5 - 3 )) && echo $(( value += 1 ))
3

Where this tends to fall short is when you want to deal with decimals.

For example with sh or bash:

$ echo $(( 2 * 2.25 ))
bash: 2 * 2.25 : syntax error: invalid arithmetic operator (error token is ".25 ")

Note, if you’re using zsh the above will work because it handles decimals, but at least for me while I do use zsh, I tend to use sh or bash in my scripts so I wouldn’t depend on zsh.

# bc Tool

Quite a few systems will have bc installed by default, but if not you can install it with your package manager of choice such as apt-get install bc, here’s a few examples:

$ bc <<< "2 + 3 - 4"
1

$ bc <<< 2+3-4
1

$ bc <<< "4 % 3"
1

$ value="$(bc <<< "3 * 5")" && echo "${value}"
15

$ bc <<< 1/4
0

$ bc -l <<< 1/4
.25000000000000000000

$ bc <<< "scale=3; 1/4"
.250

By adding the -l flag, that will configure bc to handle decimals which defaults to 20 decimal places. Alternatively you can set scale=x where x is how many decimal places you want. When you don’t supply either option it rounds down to 0 decimal places.

The bc tool can do a whole lot more, I suggest skimming man bc for more details but if you’re in a pinch to do some basic math on the command line it’s quite handy.

I used it in my invoice script and you can use it to calculate arbitrary expressions or anytime it makes sense!

The video below demos some of the commands.

# Demo Video

Timestamps

  • 0:09 – Using functionality built into your shell
  • 1:47 – Using the bc tool
  • 3:01 – Handling decimals

When was the last time you did math on the command line? Let me know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments