Do math at the commandline

Sometimes it can be handy to do simple math at the command prompt. The built-in bc command is the front-end to an "arbitrary precision calculator language" and if you work or study in a field involving mathematics it's well worth reading its man page to find out how it works. Yet, as powerful as it is, it can also be used for more trivial calculations at the command line.

To use it, type bc at the prompt. Then type in the math you want to work out, using the +, -, * (multiply), and / (divide) symbols. For example, to work out what 200 multiplied by 133 is, you would type 200*133, and then hit (Enter).

By default there are no decimal places, but this can be changed by typing scale=8, which will return results with up to eight decimal places (like a standard calculator).

Using bc interactively can be annoying for quick sums, so you can create a small shell script that takes math as an input and then run it through bc in non-interactive mode. Effectively, this is like creating your own command that will do simple math.

Start Gedit and start a new file called calc. Type the following into it:

# Run input through bc for simple math purposes scale= 'scale=8; ' # No of decimal places for result math=${scale}[email protected] echo $math|bc

Save the file and close Gedit. Then mark the script as executable and then copy it to the /usr/bin folder, so that it will be available for all users, as follows:

Following this, the script can be used from the command line, in a way similar to this:

This will add 203 and 99 and then divide by 16, returning a result of 209.1875.

To learn how to convert hexadecimal to decimal, and vice versa, see Tip 211, on page 246.

Was this article helpful?

0 0

Post a comment