How do I do <insert thing here> in bash?

Here’s another one that came from nixCraft that I use all the time. Add this to your ~/.bashrc file to create a simple to use calculator:

calc() { echo "scale=2; $*" | bc -l; }
calc_full() { echo "$*" | bc -l; }

These lines create 2 functions:

  • calc: Results are trimmed to 2 decimal places
  • calc_full: Results are not trimmed

The usage is simple:

$ calc "1024*8"       # Convert KB into MB
8192

$ calc "40*1.8+32"    # Convert Celcius to Fahrenheit
104.0

$ calc "(2+2)*(2-2)"  # You can also control the order of operation with ( )
0