Skip to content

Instantly share code, notes, and snippets.

@michaelbaudino
Last active December 6, 2016 02:06
Show Gist options
  • Save michaelbaudino/4990161 to your computer and use it in GitHub Desktop.
Save michaelbaudino/4990161 to your computer and use it in GitHub Desktop.
Bash (and probably other POSIX shells) functions and aliases to use bc directly from the prompt
### Functions to use bc from prompt
### paste this in your ~/.bashrc or ~/.bash_profile
### based on http://brettterpstra.com/2011/02/02/quick-calculations-in-bash/
# Basic functions displaying result of operations
function calc() { # Default precision used is 2
equat=$(echo ${@//[^-0-9\.\+\/\*\(\)]/ } | sed 's/[ \t]*//g')
echo -e "scale=2\n$equat\nquit\n" | bc -lq
}
function calc3() { # Default precision 3
equat=$(echo ${@//[^-0-9\.\+\/\*\(\)]/ } | sed 's/[ \t]*//g')
echo -e "scale=3\n$equat\nquit\n" | bc -lq
}
function calc4() { # Default precision 4 (you never know, it might be useful someday)
equat=$(echo ${@//[^-0-9\.\+\/\*\(\)]/ } | sed 's/[ \t]*//g')
echo -e "scale=4\n$equat\nquit\n" | bc -lq
}
# Functions copying result to clipboard instead of displaying it
function ccalc () {
calc $@ | tr -d '\n' | xclip
}
function ccalc3 () {
calc3 $@ | tr -d '\n' | xclip
}
function ccalc4 () {
calc4 $@ | tr -d '\n' | xclip
}
# Aliases, for efficiency and geekery
alias ?=calc
alias c?=ccalc
alias ?3=calc3
alias c?3=ccalc3
alias ?4=calc4
alias c?4=ccalc4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment