shell 脚本--数学运算

                              语法
方法一                expr $num1 operator $num2

方法二                $(($num1  operator $num2))

expr操作符对照表

操作符                             含义

num1 | num2       num1不为空且非0,返回num1;否则返回num2

num1 & num2       num1不为空且非0,返回num1;否者返回0

num1 < num2       num1小于num2,返回1;否则返回0

num1 <= num2      num1小于等于num2,返回1;否则返回0

num1 = num2       num1等于num2,返回1;否则返回0

num1 != num2      num1不等于num2,返回1;否则返回0

num1 > num2       num1 大于num2,返回1;否则返回0

num1 >= num2      num1大于等于num2,返回1;否则返回0

num1 + num2        求和

num1 - num2       求差

num1 / num2       求商

num1 % num2       求余

num1 * num2       求积

 

代码演示: 符号属于特殊字符 使用的时候需要转译 使用$(( ))不需要转译 $(( ))不能进行比较运算

~$ num1=30
~$ num2=50
~$ expr $num1 \| $num2
30

bc介绍

bc是bash中内建的运算器,支持浮点数运算

内建变量scale可以设置,默认是0

bc操作符对照表

操作符           含义

num1 % num2      求余

num1 ^ num2     指数运算

 bc属于内置程序 输入命令bc可以查看bc的版本

~$ which bc
/usr/bin/bc

~$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

bc的第一种使用方式

bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

23 + 5
28

23 / 5 #默认精度为0
4

scale =2  #设置精度
23 / 5
4.60

scale=6  #设置精度

23 / 5
4.600000

第二种方式在脚本中如何使用bc

# 通过管道输出给bc
~$ echo "23 + 35" | bc
58

# 通过小数点进行相加
~$ echo "23.3 + 35" | bc
58.3

# 设置精度值 用英文的  ; 进行分割,相当于两个命令
~$ echo "scale=4;23.3 / 35" | bc
.6657

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值