Bash: evaluate a mathematical term?

2019-01-17 15:16发布

问题:

echo 3+3

How can I evaluate such expressions in Bash, in this case to 6?

回答1:

in shells such as zsh/ksh, you can use floats for maths. If you need more maths power, use tools like bc/awk/dc

eg

var=$(echo "scale=2;3.4+43.1" | bc)
var=$(awk 'BEGIN{print 3.4*43.1}')

looking at what you are trying to do

awk '{printf "%.2f\n",$0/59.5}' ball_dropping_times >bull_velocities


回答2:

echo $(( 3+3 ))


回答3:

expr is the standard way, but it only handles integers.

bash has a couple of extensions, which only handle integers as well:

$((3+3))  returns 6
((3+3))   used in conditionals, returns 0 for true (non-zero) and 1 for false
let 3+3   same as (( ))

let and (( )) can be used to assign values, e.g.

let a=3+3
((a=3+3))

for floating point you can use bc

echo 3+3 | bc



回答4:

Use can make use of the expr command as:

expr 3 + 3

To store the result into a variable you can do:

sum=$(expr 3 + 3)

or

sum=`expr 3 + 3`


回答5:

Lots of ways - most portable is to use the expr command:

expr 3 + 3


回答6:

I believe the ((3+3)) method is the most rapid as it's interpreted by the shell rather than an external binary. time a large loop using all suggested methods for the most efficient.



回答7:

Solved thanks to Dennis, an example of BC-use:

$ cat calc_velo.sh

#!/bin/bash

for i in `cat ball_dropping_times`
do
echo "scale=20; $i / 59.5" | bc 
done > ball_velocities


回答8:

My understanding of math processing involves floating point processing.

Using bashj (https://sourceforge.net/projects/bashj/) you can call a java method (with floating point processing, cos(), sin(), log(), exp()...) using simply

bashj +eval "3+3"
bashj +eval "3.5*5.5"

or in a bashj script, java calls of this kind:

#!/usr/bin/bashj
EXPR="3.0*6.0"
echo $EXPR "=" u.doubleEval($EXPR)

FUNCTIONX="3*x*x+cos(x)+1"
X=3.0
FX=u.doubleEval($FUNCTIONX,$X)
echo "x="$X " => f(x)=" $FUNCTIONX "=" $FX

Note the interesting speed : ~ 10 msec per call (the answer is provided by a JVM server).

Note also that u.doubleEval(1/2) will provide 0.5 (floating point) instead of 0 (integer)