Shell中常用的几种运算,收藏自用
一、算数运算符
常用四则运算、求余数
+ 加法 - 减法 * 乘法 / 除法 % 求余
[root@yteach ~]# a=10;b=20
1、加法 +
[root@yteach ~]# echo $((a+b+10)) 40
2、减法 -
[root@yteach ~]# echo $((b-a-5)) 5
3、乘法 *
[root@yteach ~]# echo $((a*b+10)) 210
4、除法 /
[root@yteach ~]# echo $((b/a+1)) 3
5、求余 %
[root@yteach ~]# echo $((b%a)) 0
** 幂运算 ++ 自增 -- 自减
6、幂运算
[root@yteach ~]# a=2;b=3 [root@yteach ~]# echo $((a**b)) 8
7、自增运算 ++
#运算符在后面,先输出后运算 [root@yteach ~]# a=2 [root@yteach ~]# echo $((a++)) 2 [root@yteach ~]# echo $a 3 #运算符在前面,先运算后输出 [root@yteach ~]# echo $((++a)) 3
8、自减运算 - -
#运算符在后面,先输出后运算 [root@yteach ~]# a=2 [root@yteach ~]# echo $((a--)) 2 [root@yteach ~]# echo $a 1 #运算符在前面,先运算后输出 [root@yteach ~]# echo $((--a)) 1
二、算数运算命令
(()) 用于整数运算,效率高,乘法不用加转义符 let 整数运算,与(())类似 expr 整数运算 bc 计算器,可以运算整数及小数 $[] 整数运算 declare 定义变量值和属性,-i参数用于定义整形变量
1、(())运算,效率高
[root@yteach ~]a=3;b=2 [root@yteach ~]# echo $((3*4+a+4/b-3%2)) 16
2、let 运算
[root@yteach ~]# a=3;b=4 [root@yteach ~]# let c=$a+$b [root@yteach ~]# echo $c 7
3、expr 使用反引号,运算符必须用空格隔开
[root@yteach ~]# a=3;b=4 echo `expr $a + $b * 3 - 4 / 2 + 4 % 3` 14
4、 bc 计算器
[root@yteach ~]# a=3;b=4 [root@yteach ~]# echo $a+$b|bc 7 $[] [root@yteach ~]# a=3;b=4 [root@yteach ~]# echo $[a+b*a+4/2+4%3] 18
5、 declare -i
[root@yteach ~]# declare -i a=1;b=2 [root@yteach ~]# a=a+b [root@yteach ~]# echo $a 3
三、比较运算
-eq 等于 -gt 大于 -lt 小于 -ge 大于等于 -le 小于等于 -ne 不等于
四、逻辑运算符
&& 与运算(and) 真真为真,真假为假,假假为假 || 或运算(or) 真真为真,真假为真,假假为假 ! 非(取反) 非真为假,非假为真
1、 && 运算
[root@yteach ~][ 1 -gt 0 ] && [ 2 -le 3 ] && echo true || echo flase true [root@yteach ~][ 1 -le 0 ] && [ 2 -gt 1 ] && echo true || echo flase flase [root@yteach ~][ 1 -ge 2 ] && [ 2 -le 1 ] && echo true || echo flase flase
2、 || 运算
[root@yteach ~][ 1 -ge 0 ] || [ 2 -gt 1 ] && echo true || echo flase true [root@yteach ~][ 1 -ne 0 ] || [ 2 -le 1 ] && echo true || echo flase true [root@yteach ~]# [ 1 -eq 0 ] || [ 2 -eq 1 ] && echo true || echo flase flase
五、浮点运算
1、awk方法
[root@yteach ~]# a=$(awk BEGIN{print 1.23/2+3.2*2}) [root@yteach ~]# echo $a 7.015
2、bc方法
[root@yteach ~]# b=$(echo "5.21+1.314*2-1.3"|bc) [root@yteach ~]# echo $b 6.538 bc 计算除法时需要加入scale参数,否则结果不会保留小数点后面的数 [root@yteach ~]# a=`echo "scale=2;3.14/2"|bc` [root@yteach ~]# echo $a 1.57