Search Posts on Binpipe Blog

Command-line Calculator in Linux


I was toying around with the lesser used commands in Linux like the 'cal' (calendar) and then 'dc' (desktop calculator) which doesn't live up to its name and finally 'bc' which really does a good job because of its capability of handling floating point numbers. However, the problem was that its syntax is not straight-forward and doesn't simply run out-of-the-box, the way newbies and laymen would want it to be. So here's a way to create your own calculator command (we call it 'calc') and use it !

We run all the commands as root. Also we assume that the Linux box has 'bc' pre-installed in it. (Most linux distributions have 'bc' pre-installed you can check the path by the command #which bc)

Then follow these steps:
1. Create a little bash script and name it 'calc'. (Use vi / vim / nano / pico/ gedit or whatever you want to toy with)
2. Put the following contents in the script:

#!/bin/sh

bc << EOF
scale=4
$@
quit
EOF

3. Give executable permissions to the script:
#chmod +x calc


4. Move the file to /usr/bin to make it available in the shell as a command:
# mv calc /usr/bin

That's it ! The calculator is ready.

Now you can start doing calculations as in the following examples:


# calc 560 + 990
1550

#calc 10/3
3.33333 (approx)


Command-line is still interesting isn't it ? How many yeps !?

2 comments:

  1. Good Work! But there are lots of Gnome Calcs around why this commandline huh? But then it worked ;) - James

    ReplyDelete

Hi, Leave a comment here and one of the binary piper's will reply soon :)