Linux console calculator

Default featured post

Many times in Linux shell I need to do simple calculation like subtract and add but at the same time I do not want to run calculator for really simple calculation because it’s waste of time. So I was looking for an alternative which luckily I have found one. In this article, I cover how to have a simple calculator in Linux terminal.

I found expr program which stands for evaluate expressions and is very handy and useful command to do simple math calculation to logic operations like and, or, and so on. Check the example,

$ expr 10 + 20

The output will be 30 as everybody knows 😉

The important thing to know and keep in mind is that after each arguments you should add space otherwise it gives error. This means that you need to put space between 10, +, and 20.

Now take a look at more complex example,

$ mycalc=$(expr 10 + 100)

The above example stores the result of calculation into mycalc variable and then you can print it with echo like,

$ echo $mycalc

Even you can use mycalc in the next calculation such as,

$ expr $mycalc + 10

Furthermore, you can manipulate value of mycalc easily like,

$ let mycalc++
$ let mycalc--
$ let mycalc+=10

Now, let take a look at logical operations.

$ expr 10 '&' 0 # returns 0
$ expr 10 '|' 0 # returns 1
$ expr 10 '!=' 0 # returns 1
$ expr 10 '>=' 0 # returns 1

Keep in your mind that you should put operation in single quotation mark and if you do not in the first one console assumes that you want to run an operation in background because of &. In the second example above shell thinks that you want to do piping.

More information can be found in expr man page.