How can I do division with variables in a Linux sh

2019-03-08 02:27发布

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

6条回答
ゆ 、 Hurt°
2楼-- · 2019-03-08 03:09

You can use command substitution as follows:

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

Make sure spaces as mentioned above

查看更多
We Are One
3楼-- · 2019-03-08 03:16

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))
查看更多
Emotional °昔
4楼-- · 2019-03-08 03:19

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. enter code here In that case use simple strings like div or devide or something else. See the code

查看更多
欢心
5楼-- · 2019-03-08 03:29

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 $* }"; }
查看更多
淡お忘
6楼-- · 2019-03-08 03:30

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
查看更多
\"骚年 ilove
7楼-- · 2019-03-08 03:32

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
查看更多
登录 后发表回答