- Using echo “20+5” literally produces the text “20+5”.
- What command you use to get the numeric sum, 25 in this case?
- Also, what’s the easiest way to do it just using bash for floating point? For example, echo $((3224/3807.0)) prints 0 :(.
- You are looking for answers using either the basic command shell (‘command line’) itself or through using languages that are available from the command line.
You could use bc. E.g.,
Alternatively bc <<< 25+5 will also work.
Or interactively, if you want to do more than just a single simple calculation:
bc -q will jump into bc right away without the header/copyright info. For more information see the bc man page
This page also shows how to set up an alias or function to do calculation like this:
- get the result
You can use calc:
If you just enter calc with no other arguments it enters an interactive mode where you can just keep doing math.
You exit this by typing exit:
Or you use it with the expression as an argument and it will provide the answer and then exit
calc is similar to bc
There are many ways to calculate.
For simple expressions you can use bash itself:
or expr:
[ad type=”banner”]And for complex cases there is great tool bc:
bc can calculate even very complex expression with roots, logarithms, cos, sin and so on.
Integer Math:
Performing Math Calculation in Bash:
First way to do math with integer (and only integer) is to use the command “expr — evaluate expression”.
When doing a “multiply by” make sure to backslash the “asterisk” as it’s a wildcard in Bash used for expansion.
Another alternative to expr, is to use the bash builtin command let.
Also, you can simply use the parentheses or square brackets :
[ad type=”banner”]This allow you to use C-style programming :
Floating point arithmetic:
You can’t do floating point arithmetic natively in bash, you will have to use a command line tool, the most common one being “bc – An arbitrary precision calculator language”.
you can use the STDIN to send your formula to “bc” then get the output on STDOUT.
using the here-doc notation:
[ad type=”banner”]The “scale” variable is really important for the precision of your results, especially when using integers only (Note: you can also use “bc -l” to use mathlib and see the result at max scale) .
Another way to do floating point arithmetic is to use AWK:
You can use printf to adjust the precision of the results:
When using negative values, make sure to leave a white space between signs.