linux数学计算及bc命令的使用

expr命令

expr命令允许在命令行上处理数学表达式,但特别笨拙。
如下是expr支持的运算规则。
在这里插入图片描述

[root@localhost ~]# expr 1 + 5
6

但在脚本或命令行上使用它们时任然有问题出现。比如乘法运算

[root@localhost ~]# expr 2 * 3
expr: 语法错误

乘法运算符*,必须转义

[root@localhost ~]# expr 2 \* 3
6

以上是最开始使用的,幸好bash shell为了保持跟Bourne shell的兼容而保含了expr命令,但它同样也提供了一种更简单的方法来执行数学表达式,使用美元符号和方括号将数学表达式围起来。

$[expression]

[root@localhost ~]# echo $[20 + 30]
50
[root@localhost ~]# echo $[20 * 30]
600

可以发现乘法运算符也不需要转义。

bash shell数学运算符只支持整数运算

[root@localhost ~]# echo $[100 / 3]
33

浮点解决方案

最常见的方案是用内建的bash计算器bc
如果没有bc命令,如下所示,则进行安装bc即可。

[root@localhost ~]# bc
-bash: bc: 未找到命令
[root@localhost ~]# yum -y install bc

如果支持bc命令,则输入bc命令回车之后,可以输入相关数学运算,并支持浮点数

[root@localhost ~]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
3 * 2.1
6.3

退出按quit
说明:浮点运算是由内建变量scale控制的。必须将这个值设置为你希望在计算结果中保留的小数位数,否则无法得到期望的结果。
bc的帮助手册

[root@localhost ~]# bc --help
usage: bc [options] [file ...]
  -h  --help         print this usage and exit
  -i  --interactive  force interactive mode
  -l  --mathlib      use the predefined math routines
  -q  --quiet        don't print initial banner
  -s  --standard     non-standard bc constructs are errors
  -w  --warn         warn about non-standard bc constructs
  -v  --version      print version information and exit

测试:

[root@localhost ~]# bc -q
100 / 3
33
scale=4
100 / 3
33.3333

scale变量默认值是0,所以100/3没有看到小数部分。设置scale=4之后,显示出了四位小数。
bc命令还支持变量

[root@localhost ~]# bc -q
num=5
num * 2.2
11.0

在脚本中使用bc

variable=$(echo “options; expression” | bc)

举例:
[root@localhost hbk]# cat bc.sh
#!/bin/bash
num=$(echo “scale=3; 100 / 3”|bc)
echo 100 / 3 = $num
[root@localhost hbk]# chmod u+x bc.sh
[root@localhost hbk]# ./bc.sh
100 / 3 = 33.333

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄宝康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值