Divide two variables in bash

Divide two variables in bash

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

its better to use bc:

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

output:
.75

scale is the precision required

If you want to do it without bc, you could use awk:

$ awk -v var1=3 -v var2=4 BEGIN { print  ( var1 / var2 ) }
0.75

Divide two variables in bash

There are two possible answers here.

To perform integer division, you can use the shell:

$ echo $(( var1 / var2 ))
0

The $(( ... )) syntax is known as an arithmetic expansion.

For floating point division, you need to use another tool, such as bc:

$ bc <<<scale=2; $var1 / $var2
.75

The scale=2 statement sets the precision of the output to 2 decimal places.

Leave a Reply

Your email address will not be published.