linux——shell 中的运算

运算方式及运算符号

运算符号意义
+,-加法,减法
*,/,%乘法,除法,取余
**幂运算
++,- -自增加,自减少
<,<=,>,>=比较符号
=,+=,-=,*=,/=,%=赋值运算,例如a+=1,相当于a=a+1

SHELL 中常用的运算命令

运算操作与运算命令含义
(( ))用于整数运算
let用于整数运算,与(())类似
expr用于整数运算,功能相对较多
bclinux 下的计算器,适合整数及小数运算
$[ ]用于整数运算

示例用法

这里写图片描述

[root@desktop27 mnt]# (( a=1+1 ))
[root@desktop27 mnt]# echo $a
2
[root@desktop27 mnt]# let a=1+2
[root@desktop27 mnt]# echo $a
3
[root@desktop27 mnt]# a=1+1
[root@desktop27 mnt]# echo $a
1+1
[root@desktop27 mnt]# echo `expr 1 + 1`
2
[root@desktop27 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'. 
2+3
5
quit
[root@desktop27 mnt]# bc << EOF
> 2+3
> EOF
5
[root@desktop27 mnt]# echo $[1+1]
2
[root@desktop27 mnt]#
10 秒倒计时脚本
[root@desktop27 mnt]# vim time.sh 
[root@desktop27 mnt]# cat time.sh 
#!/bin/bash
for ((Time;Time>0;Time--))
do
    echo -n "after $Time's is end "
    echo -ne "\r    \r"
    sleep 1
done
[root@desktop27 mnt]# sh time.sh
after 8's is end

这里写图片描述

倒计时脚本一(可自定义倒计时时间)
##不建议使用
[root@desktop27 mnt]# vim time1.sh
[root@desktop27 mnt]# cat time1.sh 
#!/bin/bash
read -p "Please input minutes: " MIN
read -p "Please input seconds: " SEC
((NUM=MIN*60+SEC))
for (($NUM;NUM>0;NUM--))

do
    let FF=NUM/60
    let MM=NUM%60
    echo -ne "\r$FF:$MM \r"
    sleep 1

done
[root@desktop27 mnt]#
倒计时脚本二(可自定义倒计时时间)
[root@desktop27 mnt]# vim time.sh 
[root@desktop27 mnt]# cat time.sh 
#!/bin/bash
PRING_MESSAGE()
{
    echo -n "$MIN:$SEC "
    echo -ne "\r    \r"
    sleep 1
}
read -p "Please input MIN: " MIN
read -p "Please input SEC: " SEC
for ((;SEC>=0;SEC--))
do
    [ "$SEC" = "0" -a "$MIN" = "0" ]&& exit 0
    [ "$SEC" = "0" -a "$MIN" -gt "0" ]&&{
    PRING_MESSAGE
    ((MIN--))
    SEC=59
    }
    PRING_MESSAGE
done
[root@desktop27 mnt]# sh time.sh 
Please input MIN: 1
Please input SEC: 10
1:7

这里写图片描述

用脚本制作一个计算器,要求如下:

执行 Calculator.sh 后显示
Please input first number:
Please input the operation:
Please input second number:
执行后显示操作后的数值

[root@desktop27 mnt]# vim Calculator.sh
[root@desktop27 mnt]# cat Calculator.sh 
#!/bin/bash
read -p "Please input first number: " FIRST
read -p "Please input the operation: " OPER
read -p "Please input second number: " SECOND
bc <<EOF
$FIRST$OPER$SECOND
EOF
[root@desktop27 mnt]# sh Calculator.sh 
Please input first number: 4
Please input the operation: +
Please input second number: 2
6
[root@desktop27 mnt]# 

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值