Linux Shell 数学运算
在Linux中直接使用数学运算符进行数学运算往往得不到我们想要的计算结果。要在Shell中进行数学运算,我们需要借助点小手段。目前,Linux Shell中进行数学运算的方法主要有三种:bc、expr、let。
1 bc
1.1 命令行方式
在bash界面,直接输入bc或者bc -q,就可以进去bc的命令行,通过使用数学运算符能够得到我们想要的结果:
[scott@centos1 ~]$ bc -q
2+4
6
2-4
-2
2*4
8
2/4
0
2%4
2
2^4
16
scale=2;2/4
.50
2%4
0
scale=0;2/4
0
2%4
2
输入运算数和运算符号,回车即可得到运算结果。通过设置scale,可以定义当前的小数点精度,对除法、取余和幂运算有效。
这种方式只能在bc的命令行中进行,在代码中当然不能这样干了。
1.2 管道方式
[scott@centos1 ~]$ echo 2+3|bc
5
[scott@centos1 ~]$ echo 2-3|bc
-1
[scott@centos1 ~]$ echo 2*3|bc
6
[scott@centos1 ~]$ echo 2/3|bc
0
[scott@centos1 ~]$ echo 2%3|bc
2
[scott@centos1 ~]$ echo "scale=2;2/3"|bc
.66
[scott@centos1 ~]$ echo "scale=2;2%3"|bc
.02
[scott@centos1 ~]$ echo "scale=2;3/2"|bc
1.50
[scott@centos1 ~]$ echo "scale=2;3%2"|bc
0
[scott@centos1 ~]$ echo 2^3|bc
8
这种管道方式在shell中应用的更多一些,同样可以在运算的时候加上精度的限制。
1.3 进制转换
[scott@centos1 ~]$ echo "ibase=10;15"|bc
15
[scott@centos1 ~]$ echo "ibase=8;15"|bc
13
[scott@centos1 ~]$ echo "ibase=16;F"|bc
15
上文的例子,是把几种进制都转化为10进制。
1.4 表达式运算
[scott@centos1 ~]$ vim bc-test.bc
[scott@centos1 ~]$ bc -q bc-test.bc
3
-1
6
0
.75
0
其中,bc-test.bc的内容为:
1+2
1-2
2*3
2/3
scale=2;3/4
scale=0;3/4
就是表达式的集合。
2 expr
expr是个很强大的命令,可以进行数学运算,也可以进行字符串的操作等。先看下数学运算的功能。
[scott@centos1 ~]$ expr 3+4
3+4
[scott@centos1 ~]$ expr 3 +4
expr: syntax error
[scott@centos1 ~]$ expr 3 + 4
7
[scott@centos1 ~]$ expr 3 * 4
expr: syntax error
[scott@centos1 ~]$ expr 3 \* 4
12
[scott@centos1 ~]$ expr 3 / 4
0
[scott@centos1 ~]$ expr 3 % 4
3
expr不支持浮点运算,不支持幂乘运算,在运算的时候可要注意运算符和运算数的分离,写在一起可是不识别的,另外,乘法有点特殊,需要转义。
下面看看expr的字符串操作。
[scott@centos1 ~]$ string=123456789asdfg
[scott@centos1 ~]$ expr length $string
14
[scott@centos1 ~]$ expr index $string '456'
4
[scott@centos1 ~]$ expr substr $string 7 4
789a
[scott@centos1 ~]$ expr substr $string 7 11
789asdfg
上例分别利用expr命令进行了计算字符串长度、获取字串或者字符的首次出现位置、取指定位置开始的限定长度的字符字串,需要注意的是expr中的下标是从1开始的。
3 let
[scott@centos1 ~]$ let a=2+3
[scott@centos1 ~]$ echo $a
5
[scott@centos1 ~]$ let a=2*3
[scott@centos1 ~]$ echo $a
6
[scott@centos1 ~]$ let a=2/3
[scott@centos1 ~]$ echo $a
0
[scott@centos1 ~]$ let a=2%3
[scott@centos1 ~]$ echo $a
2
[scott@centos1 ~]$ let a=2^3
[scott@centos1 ~]$ echo $a
1
[scott@centos1 ~]$ let a=2**3
[scott@centos1 ~]$ echo $a
8
需要注意的是,let命令里的幂乘运算不是^,而是**。
4 其他方式
[scott@centos1 ~]$ echo $((3+5))
8
[scott@centos1 ~]$ echo $((3*5))
15
[scott@centos1 ~]$ echo $((3**5))
243
[scott@centos1 ~]$ echo $((((3+5))*3))
24
[scott@centos1 ~]$ echo `date`
Fri Aug 16 08:24:33 PDT 2013
[scott@centos1 ~]$ echo `date +%Y%m%d`
20130816