How can I do division with variables in a Linux shell?

Judking picture Judking · Aug 7, 2013 · Viewed 330.4k times · Source

When I run commands in my shell as below, it returns an expr: non-integer argument error. Can someone please explain this to me?

$ x=20
$ y=5
$ expr x / y 
expr: non-integer argument

Answer

paddy picture paddy · Aug 7, 2013

Those variables are shell variables. To expand them as parameters to another program (ie expr), you need to use the $ prefix:

expr $x / $y

The reason it complained is because it thought you were trying to operate on alphabetic characters (ie non-integer)

If you are using the Bash shell, you can achieve the same result using expression syntax:

echo $((x / y))

Or:

z=$((x / y))
echo $z