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

前端 未结 6 1054
南旧
南旧 2020-12-22 20:38

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
$          


        
6条回答
  •  死守一世寂寞
    2020-12-22 20:53

    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
    

提交回复
热议问题