qc: quick calculator
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/bashpython -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-18.8$ qc 2**416
In reality, this script is just a glorified alias of python -c
, but importing the math library makes this command considerably more powerful.
#!/bin/bashpython -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 OSXpython -c "from math import *; print $1" | pbcopypbpaste # show the result in bash
On Linux, a few lines of python will accomplish the same task.
#!/bin/bash# code for Linuxpython -c "from math import *import pygtkpygtk.require('2.0')import gtkevaluated = $1clipboard = 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.
Recommended
Python Fabric
To help facilitate my blogging workflow, I wanted to go from written to published post quickly. My general workflow for writing a post for [this...
Managing bash aliases
Bash aliases are great. Whether you use them to quickly connect to servers or just soup up the standard bash commands, they are a useful tool for...
Sandboxed Python Environment
Disclaimer: I am not a security expert or a security professional.