Home / How-to Guides / Command line Calculator on Unix, Linux and Mac

Command line Calculator on Unix, Linux and Mac

I mostly use terminal windows to do most of my things. Even when I need to do some calculations or arithmetic operations, I prefer doing it on terminal command line. When every thing could be done using terminal then why to use GUI calculator. One of the most useful feature or the best part of using this, it helps you to solve complex calculations or  arithmetic operations on the command line. It become very hard to solve some complex arithmetic operations using calculator with confusing brackets and braces and you end up with wrong result. Calculating on command line will display all the expression on single line which makes you see what you have typed and will prevent you from typo mistake.

Command line Calculator on Unix, Linux and Mac

This function is created with the help of bash shell. Bash Shell comes by default in Linux, Unix, MAC and It can also work with Microsoft window using Cygwin. Check my previous article on “Calculate using DOS Command in windows”  To create Calculator, enter the below function on the command line. Add this function command to ~/.bashrc, so that you don’t need to retype this function again after restarting the terminal.

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

 

Now simply type “calc” followed by the calculation you want to perform. If you are using space or special character, make sure you add quotes to your calculation or expression, otherwise you’ll get an error. A simple e.g. ofCommand line Calculator - Techie Inspire arithmetic operation, 10+20-20*10/10 gives the output as 10. For complex expression you can use parenthesis or brackets but don’t forget to put quotes to your expression or you will end up with error, check the image beside. Below are some example of such arithmetic operation using terminal command line.

calc 10*(20/10) answer is 20

calc “(20*10)/2+100” answer is 200

calc “((4+(2*3))/ 9)- 45.20” answer is –44.08888

This will also work on windows using Cygwin, but I have never tested this using Cygwin. Did the above trick was useful and informative to you. If you find this useful, make a little more effort by sharing and spreading the knowledge to others.

About Kroshan

Roshan Karkera a.k.a. k.roshan. Blogger by passion and software engineer by profession. He believes in sharing knowledge, which made him to start his own blog. He is very much keen & passionate about new technology & Science. If you'd like to connect with him, follow at Google plus or Twitter.
  • Anonymous

    That will help me, i generally work on terminal

  • AMY

    that is working for me, at least its not ignoring decimal value and its able to calculate difficult expression too.