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

旧街凉风 提交于 2019-11-28 15:00:24

问题


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

回答1:


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



回答2:


I believe it was already mentioned in other threads:

calc(){ awk "BEGIN { print "$*" }"; }

then you can simply type :

calc 7.5/3.2
  2.34375

In your case it will be:

x=20; y=3;
calc $x/$y

or if you prefer, add this as a separate script and make it available in $PATH so you will always have it in your local shell:

#!/bin/bash
calc(){ awk "BEGIN { print $* }"; }



回答3:


Why not use let; I find it much easier. Here's an example you may find useful:

start=`date +%s`
# ... do something that takes a while ...
sleep 71

end=`date +%s`
let deltatime=end-start
let hours=deltatime/3600
let minutes=(deltatime/60)%60
let seconds=deltatime%60
printf "Time spent: %d:%02d:%02d\n" $hours $minutes $seconds



回答4:


Referencing Bash Variables Requires Parameter Expansion

The default shell on most Linux distributions is Bash. In Bash, variables must use a dollar sign prefix for parameter expansion. For example:

x=20
y=5
expr $x / $y

Of course, Bash also has arithmetic operators and a special arithmetic expansion syntax, so there's no need to invoke the expr binary as a separate process. You can let the shell do all the work like this:

x=20; y=5
echo $((x / y))



回答5:


let's suppose

x=50
y=5

then

z=$((x/y))

this will work properly . But if you want to use / operator in case statements than it can't resolve it. In that case use simple strings like div or devide or something else. See the code




回答6:


To get the numbers after decimal point, you can do this:-

read num1 num2
div=`echo $num1 / $num2 |bc -l`
echo $div



回答7:


You can use command substitution as follows:

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

Make sure spaces as mentioned above



来源:https://stackoverflow.com/questions/18093871/how-can-i-do-division-with-variables-in-a-linux-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!