If you spend most of your time in the command line, you don’t want to leave to do math. Qc is a script that does in-line command line math without forcing you to exit the main bash prompt as you might with a program like bc
or a language interpreter.
#!/bin/bash
python -c "print $1"
Make the script executable with the command:
$ chmod +x qc.sh
Alias it to qc
by editing the .bash_profile
file in your home folder and adding the code:
alias qc="~/path/to/qc.sh"
Use qc as follows:
$ qc 7-8
-1
$ qc 9.8-1
8.8
$ qc 2**4
16
In reality, this script is just a glorified alias of python -c
, but importing the math library makes this command considerably more powerful.
#!/bin/bash
python -c "from math import *; print $1"
This wildcard import gives access to constants such as pi
and e
in calculations, but more notably, it also allows for the use of functions in calculations. For example:
$ qc "factorial(10)"
3628800
$ qc "hex(255)"
0xff
$ qc "sin(pi/7)"
0.433883739118
Because qc is executed in bash, it requires quotes (single or double) to be placed around expressions with functions, since bash will try to evaluate expressions in parentheses before it does anything else. The quotes tell bash to pass the entire expression as a whole to qc
instead of trying to evaluate part of it beforehand.
Finally, once you have the result of a calculation, the pbcopy
command places the result in the clipboard for ease of use.
#!/bin/bash
# code for OSX
python -c "from math import *; print $1" | pbcopy
pbpaste # show the result in bash
On Linux, a few lines of python will accomplish the same task.
#!/bin/bash
# code for Linux
python -c "from math import *
import pygtk
pygtk.require('2.0')
import gtk
evaluated = $1
clipboard = gtk.clipboard_get()
clipboard.set_text('%s' % str(evaluated))
clipboard.store()
print(evaluated)"
Edit 7/23: changed eval
to evaluated
in the code to avoid conflict with the bash builtin.
The script determines which copy commands to use based on your OS. The full script is available on Github.