如何在Linux shell中对变量进行除法?

Jud*_*ing 123 linux variables bash shell division

当我在shell中运行命令时,它会返回expr: non-integer argument错误.有人可以向我解释一下吗?

$ x=20
$ y=5
$ expr x / y 
expr: non-integer argument
Run Code Online (Sandbox Code Playgroud)

pad*_*ddy 177

那些变量是shell变量.要将它们作为参数扩展到另一个程序(即 expr),您需要使用$前缀:

expr $x / $y
Run Code Online (Sandbox Code Playgroud)

它抱怨的原因是因为它认为你试图对字母字符进行操作(即非整数)

如果您使用的是Bash shell,则可以使用表达式语法获得相同的结果:

echo $((x / y))
Run Code Online (Sandbox Code Playgroud)

要么:

z=$((x / y))
echo $z
Run Code Online (Sandbox Code Playgroud)

  • 必须注意的是,在本页的某处,大多数(如果不是全部)GNU/Linux shell**只执行整数运算**. (52认同)
  • 您可以通过阅读 bash 的手册页找到很多信息。在提示符下输入 `man bash`(`q` 退出) (2认同)

小智 32

我相信它已经在其他主题中提到:

calc(){ awk "BEGIN { print "$*" }"; }
Run Code Online (Sandbox Code Playgroud)

然后你可以简单地输入:

calc 7.5/3.2
  2.34375
Run Code Online (Sandbox Code Playgroud)

在你的情况下,它将是:

x=20; y=3;
calc $x/$y
Run Code Online (Sandbox Code Playgroud)

或者如果您愿意,可以将其作为单独的脚本添加并在$ PATH中使用,这样您将始终在本地shell中使用它:

#!/bin/bash
calc(){ awk "BEGIN { print $* }"; }
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用`echo'1/3'| bc -l` (4认同)

小智 19

为什么不使用let; 我发现它容易得多.以下是您可能会发现有用的示例:

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
Run Code Online (Sandbox Code Playgroud)


Tod*_*obs 15

引用Bash变量需要参数扩展

大多数Linux发行版的默认shell是Bash.在Bash中,变量必须使用美元符号前缀进行参数扩展.例如:

x=20
y=5
expr $x / $y
Run Code Online (Sandbox Code Playgroud)

当然,Bash也有算术运算符和特殊的算术扩展语法,因此不需要将expr二进制文件作为单独的进程调用.你可以让shell完成所有这样的工作:

x=20; y=5
echo $((x / y))
Run Code Online (Sandbox Code Playgroud)


小智 5

要获得小数点后的数字,您可以这样做:-

read num1 num2
div=`echo $num1 / $num2 | bc -l`
echo $div
Run Code Online (Sandbox Code Playgroud)