Bash: evaluate a mathematical term?

Solution 1:

echo $(( 3+3 ))

Solution 2:

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

Solution 3:

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

Solution 4:

You 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`

Solution 5:

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

expr 3 + 3