Shell脚本-5 运算

一、运算方式及运算符号

+-                加法,减法
*,/,%             乘法,除法,取余
**                  幂运算
++--              自加一,自减一
<,<=,>,>=           比较大小
=,+=,-=,*=,/=,%=   赋值运算(例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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值