HomeHow-to GuidesCommand-Line Calculator on Linux, Unix and Mac (Terminal)

Command-Line Calculator on Linux, Unix and Mac (Terminal)

I do most of my work in a terminal window, so when I need to do a quick calculation, I prefer to do it on the command line instead of opening a calculator app. It’s also handy for complex calculations.

Command line Calculator on Unix, Linux and Mac_thumb[4]

With a graphical calculator, it’s hard to enter long expressions with brackets, and one wrong bracket gives you the wrong result. On the command line, the whole expression is shown on one line, so you can see exactly what you typed and avoid typos.

The trick below uses a small shell function. It works in bash (the default shell on most Linux distributions) and in zsh (the default shell on macOS since Catalina). On Windows, you can use it in WSL or Cygwin. For a Windows-only method, see our guide on how to calculate using the Command Prompt in Windows.

How to Create a Command-Line Calculator

Type the following function in your terminal:

calc(){ awk "BEGIN{ print $* }" ;}

To keep the function after you close the terminal, add the same line to your ~/.bashrc file (Linux, bash) or ~/.zshrc file (macOS, zsh), then open a new terminal window.

Command line Calculator Linux

How to Use It

Type calc followed by the calculation. Always put the expression in straight quotes ("..."), especially if it contains spaces, brackets or the * sign; otherwise the shell may misread it and show an error.

Examples:

calc "10+20-20*10/10"        → 10
calc "10*(20/10)"            → 20
calc "(20*10)/2+100"         → 200
calc "((4+(2*3))/9)-45.20"   → -44.0889

Tip: Linux and macOS also include the built-in calculator bc. For example, echo "scale=4; 10/3" | bc prints 3.3333.

If you found this trick useful, please share it with others.

Roshan Karkera
Roshan Karkera
Roshan Karkera is a passionate blogger and a software engineer by profession, driven by a love for technology, science, and continuous learning. With a strong belief in sharing knowledge, he started this blog to inspire and inform readers through simple, insightful content. When he's not coding or exploring the latest in tech, you’ll find him writing about ideas that matter. Connect with him on Twitter or your favorite social platform to stay updated.
RELATED ARTICLES

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular