67

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?

1

5 Answers 5

112

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

3
  • The output of bc should be a string or a float number?
    – Sigur
    Oct 1, 2017 at 0:45
  • 2
    @Sigur the output is always a string
    – m47730
    Oct 2, 2017 at 11:12
  • 2
    Is it possible to convert it to float or int?
    – Sigur
    Oct 2, 2017 at 11:31
25
+50

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
2
19

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.

1
  • 1
    P.S. in my .zshrc, I have calc () { echo "scale=2;$*" | bc | sed 's/\.0*$//'} to do calculations. The latter sed is to remove trailing zeros, E.g. 100/10 we get 10 instead of 10.00...
    – Kent
    May 22, 2015 at 13:47
2
#!/bin/bash
var1=10
var2=5
echo $((var1/var2))
1
  • 2
    It would be nice if you explain what the error was.
    – MarkoHiel
    May 22, 2015 at 14:50
2

You can also use Python for this task.
Type python -c "print( $var1 / float($var2) )"

1
  • This is honestly the simplest solution I could get working. The bc solution wasn't working at all for me.
    – muad-dweeb
    Jun 9, 2022 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.