Multiplication of two numbers using expr in shell script In shell, * represents all files in the current directory. So, in order to use * as a multiplication operator, we should escape it like \*. If we directly use * in expr, we will get error message.
bc command is used for command line calculator. It is similar to basic calculator by using which we can do basic mathematical calculations. Arithmetic operations are the most basic in any kind of programming language.
Yes, you can use bash's built-in Arithmetic Expansion $(( ))
to do some simple maths
$ echo "$((5 * 5))"
25
Check the Shell Arithmetic section in the Bash Reference Manual for a complete list of operators.
For sake of completeness, as other pointed out, if you need arbitrary precision, bc
or dc
would be better.
For more advanced and precise math consider using bc(1).
echo "3 * 2.19" | bc -l
6.57
Bash supports arithmetic expansion with $(( expression ))
. For example:
$ echo $(( 5 * 5 ))
25
A number of utilities provide arithmetic, including bc and expr.
$ echo '5 * 5' | /usr/bin/bc
25
$ /usr/bin/expr 5 \* 5
25
The classical solution is:
expr 5 \* 5
expr
will only work with integer operands. Another nice option is:
echo 5 5\*p | dc
dc
can be made to work with non-integer operands.
A simple shell function (no sed needed) should do the trick of interpreting '5X5'
$ function calc { bc -l <<< ${@//[xX]/*}; };
$ calc 5X5
25
$ calc 5x5
25
$ calc '5*5'
25
I use this function which uses bc
and thus supports floating point calculations:
c () {
local a
(( $# > 0 )) && a="$@" || read -r -p "calc: " a
bc -l <<< "$a"
}
Example:
$ c '5*5'
25
$ c 5/5
1.00000000000000000000
$ c 3.4/7.9
.43037974683544303797
Bash's arithmetic expansion doesn't support floats (but Korn shell and zsh do).
Example:
$ ksh -c 'echo "$((3.0 / 4))"'
0.75
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With