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

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.


Bash can do the math itself to some extent. It's not useful for accuracy, though, as it rounds.

[user]$ echo $(( 10/5 ))
2

But you're exactly right - a bash function would be a simple shortcut and your example basically works.

divide() {
  echo "scale=25;$1/$2" | bc
}

Throw that in your .bashrc and then you can:

[user]$ divide 10 5
2.0000000000000000000000000

You probably know the bash builtin 'expr' as in

$ expr 60 / 5
12

which is limited to integers and needs the spaces between the arguments.

What is keeping you from defining a function along the lines of the echo expression you're already using? I.e.

 divide () {
   echo $1/$2 | bc
 }