Bash – Doing simple math on the command line using bash functions: $1 divided by $2 (using bc perhaps)

arithmeticbashrcbccommand linefunction

Sometimes I need to divide one number by another. It would be great if I could just define a bash function for this. So far, I am forced to use expressions like

echo 'scale=25;65320/670' | bc

but it would be great if I could define a .bashrc function that looked like

divide () {
  bc -d $1 / $2
}

Best Answer

I have a handy bash function called calc:

calc () {
    bc -l <<< "$@"
}

Example usage:

$ calc 65320/670
97.49253731343283582089

$ calc 65320*670
43764400

You can change this to suit yourself. For example:

divide() {
    bc -l <<< "$1/$2"
}

Note: <<< is a here string which is fed into the stdin of bc. You don't need to invoke echo.

Related Question