Divide two variables in bash

Mathias Verhoeven picture Mathias Verhoeven · May 22, 2015 · Viewed 71k times · Source

I am trying to divide two var in bash, this is what I've got:

var1=3;
var2=4;

echo ($var1/$var2)

I always get a syntax error. Does anyone knows what's wrong?

Answer

m47730 picture m47730 · May 22, 2015

shell parsing is useful only for integer division:

var1=8
var2=4
echo $((var1 / var2))

output: 2

instead your example:

var1=3
var2=4
echo $((var1 / var2))

ouput: 0

it's better to use bc:

echo "scale=2 ; $var1 / $var2" | bc

output: .75

scale is the precision required