一、运算方式及运算符号
+,- 加法,减法
*,/,% 乘法,除法,取余
** 幂运算
++,-- 自加一,自减一
<,<=,>,>= 比较大小
=,+=,-=,*=,/=,%= 赋值运算(例a+=1,即a=a+1)
二、SHELL中常用的运算命令
(()) 用于整数运算
let 用于整数运算,与(())类似
expr 用于整数运算,功能相对较多
bc linux下的计算器,适合整数及小数运算
$[] 用户整数运算
示例:
[root@host2 ~]# echo $[ 5/3 ]
1
[root@host2 ~]# echo $[ 5**3 ]
125
[root@host2 ~]# echo $[ 5**2 ]
25
[root@host2 ~]# echo $[ 5%3 ]
2
[root@host2 ~]# echo $[ 5*3 ]
15
[root@host2 mnt]# vim test.sh
[root@host2 mnt]# cat test.sh
#!/bin/bash
for ((i=10;i>0;i--))
do
((n+=i))
echo $n
done
[root@host2 mnt]# sh test.sh
10
19
27
34
40
45
49
52
54
55
[root@host2 mnt]# vim test.sh
[root@host2 mnt]# cat test.sh
#!/bin/bash
for ((i=10;i>0;i--))
do
((n-=i))
echo $n
done
[root@host2 mnt]# sh test.sh
-10
-19
-27
-34
-40
-45
-49
-52
-54
-55
[root@host2 mnt]# a=1
[root@host2 mnt]# b=2
[root@host2 mnt]# let c=$a+$b
[root@host2 mnt]# echo $c
3
[root@host2 mnt]# expr $a + $b
3
[root@host2 mnt]# 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
5
quit
[root@host2 mnt]# vim test.sh
[root@host2 mnt]# cat test.sh
#!/bin/bash
bc <<EOF
7.7+4.2
EOF
[root@host2 mnt]# sh test.sh
11.9
[root@host2 mnt]# let A=1+1
[root@host2 mnt]# echo $A
2
[root@host2 mnt]# echo `expr 3+4`
3+4
脚本:1分10秒倒计时
[root@host2 mnt]# vim time_end.sh
[root@host2 mnt]# cat time_end.sh
#!/bin/bash
MIN=1
SEC=10
let TIME=(MIN*60)+SEC
for ((TIME=$TIME;TIME>0;TIME--))
do
M_TIME=$[ $TIME/60 ]
S_TIME=$[ $TIME%60 ]
echo -n "After $M_TIME:$S_TIME "
echo -ne "\r \r"
sleep 1
done
[root@host2 mnt]# sh time_end.sh
^Cter 1:9
[root@host2 mnt]# sh time_end.sh
^Cter 0:52