自带的运算命令:expr
1
2
3
4
5
6
7
8
9
10
|
[root@www ~]
# expr 1 + 5 加
6
[root@www ~]
# expr 20 - 5 减
15
[root@www ~]
# expr 20 \* 5 乘
100
[root@www ~]
# expr 20 \/ 5 除
4
[root@www ~]
# expr 22 \% 5 余
2
|
1
2
3
4
5
6
7
8
|
[root@www ~]
# v1=10
[root@www ~]
# v2=20
[root@www ~]
# v3=`expr $v2 / $v1`
[root@www ~]
# echo $v3
2
[root@www ~]
# v1=$[1 + 5]
[root@www ~]
# echo $v1
6
|
浮点计算:bc
安装bc
[root@www ~]# yum -y install bc.x86_64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
[root@www ~]
# 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'.
1.2 * 2.1
#计算1.2乘以2.1的结果
2.5
1.2 * 2.10
2.52
3 / 2
1
scale=4
//
设置计算结果保留的小数位数,scale默认的值为0
3 / 2
1.5000
5 / 3
1.6666
|
1
2
3
4
5
6
7
8
|
[root@www ~]
# bc -q #-q屏蔽打开bc计算器时的软件说明
1.3 / 2
0
scale=4
1.3 / 2
.6500
2 / 1.5
1.3333
|
bc中引用赋值变量:
1
2
3
4
5
6
7
8
9
|
[root@www ~]
# bc -q
scale=4
a1=2016
a1 * 20
40320
b1 = a1 / 365
print b1
5.5232
quit
#退出
|
在脚本中使用bc:
1
|
基本格式:variable(变量)=`
echo
"options;expression"
|
bc
`
|
1
2
3
4
5
6
7
|
[root@www ~]
# vim test.sh
#!/bin/bash
v1=`
echo
"scale=4; 3 / 2"
|
bc
`
echo
v1=$v1
[root@www ~]
# sh test.sh
v1=1.5000
|
1
2
3
4
5
6
7
8
9
|
[root@www ~]
# vim test.sh
#!/bin/bash
v1=2016
v2=365
v3=`
echo
"scale=4; $v1 / $v2"
|
bc
`
echo
v3=$v3
[root@www ~]
# sh test.sh
v3=5.5232
|
1
2
3
4
5
6
7
8
9
10
|
[root@www ~]
# cat test.sh
#!/bin/bash
v1=2016
v2=365
v3=`
echo
"scale=4; $v1 / $v2"
|
bc
`
v4=`
echo
"scale=4; $v3 * $v2"
|
bc
`
echo
v4=$v4
[root@www ~]
# sh test.sh
v4=2015.9680
|
bc内联输入重定向:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
[root@www ~]
# cat test.sh
#!/bin/bash
v1=2016
v2=365
v3=10
v4=5000
v5=`
bc
<< EOF
scale = 4
a1 = ( $v4 / $v2 )
a2 = ( $v3 * $v2 )
a1 + a2
EOF
`
echo
v5=$v5
[root@www ~]
# sh test.sh
v5=3663.6986
|
本文转自 HMLinux 51CTO博客,原文链接:http://blog.51cto.com/7424593/1733358