一.shell中的基本运算操作与命令 (()) 用于整数的运算 let 用于整数的运算,与(())类似 expr 用于整数的运算,功能相对较多 bc linux下的计算器,适合整数及小数的运算 $[ ] 用户整数的运算 二.基本运算命令的认识 1.(())的用法
[root@server mnt]# ((a=1+1)) [root@server mnt]# echo $a 22.let的用法
[root@server mnt]# let a=1+1 [root@server mnt]# echo $a 23.expr的用法
[root@server mnt]# expr 1 + 1 24.bc的用法
[root@server 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'. 1+1 2 exit 0 quit5.$[ ]的用法
[root@server mnt]# echo $[1+1] 2三.基本运算命令的应用 1.对数字进行倒序输出
[root@server mnt]# vim test1.sh [root@server mnt]# cat test1.sh #!/bin/bash for ((i=10;i>0;i--)) do echo $i done [root@server mnt]# sh test1.sh 10 9 8 7 6 5 4 3 2 12.对10s进行倒计时
[root@server mnt]# vim time.sh [root@server mnt]# cat time.sh #!/bin/bash for i in {10..1} ##设置范围 do echo -n "After $i's is end" ##-n不换行输出 echo -ne "\r" ##使下一次输出覆盖上一次输出 sleep 1 ##间隔1s输出 done3.对分秒进行倒计时 (1)用户输入分钟数 和 秒数,例如进行1分10秒的倒计时,输入分钟数 1 ;秒数 10
[root@server mnt]# vim time.sh [root@server mnt]# cat time.sh #!/bin/bash MIN=1 SEC=20 ALL_SEC=$(($MIN*60+$SEC)) ##将分秒换算成秒 for ((sec=$ALL_SEC;sec>0;sec--)) ##设定循环条件 do M=$[$sec/60] ##计算倒计时分钟输出的值 S=$[sec`] ##计算倒计时秒输出的数值 echo -n "$M $S" ##不换行输出分 秒 echo -ne "\r" ##下一次输出覆盖上一次 sleep 1 ##间隔1s done(2)对任意分秒进行倒计时 方法1
[root@server mnt]# vim time.sh [root@server mnt]# cat time.sh #!/bin/bash read -p "Please input the min:" MIN read -p "Please input the sec:" SEC ALL_SEC=$(($MIN*60+$SEC)) for ((sec=$ALL_SEC;sec>0;sec--)) do M=$[$sec/60] S=$[sec`] echo -n "$M $S" echo -ne "\r" sleep 1 done方法2
[root@server mnt]# vim time.sh [root@server mnt]# cat time.sh #!/bin/bash read -p "Please input the min:" MIN read -p "Please input the sec:" SEC for ((;SEC>=0;SEC--)) do if [ "$MIN" = "0" -a "$SEC" = "0" ] then exit elif [ "$SEC" = "0" -a "$MIN" -gt "0" ] then echo -n "$MIN : $SEC" sleep 1 echo -ne "\r" ((MIN--)) SEC=60 else echo -n "$MIN : $SEC" echo -ne "\r" sleep 1 fi done4.编辑一个计算器 执行Calculator.sh后显示: 请输入你要操作的数字: 请输入你要操作的动作: 请输入你要操作的第二个数字: 执行后显示操作后的数字 方法1
[root@server mnt]# vim Calculator.sh [root@server mnt]# cat Calculator.sh #!/bin/bash read -p "Plese input number 1:" NUM1 ##输入第1个数字 read -p "Please input your action:" ACTION ##输入动作 read -p "Please input number 2:" NUM2 ##输入第2个数字 ((RESULT=$NUM1$ACTION$NUM2)) ##进行运算 echo " The result is $RESULT" ##输出结果测试
[root@server mnt]# sh Calculator.sh Plese input number 1:2 Please input your action:* Please input number 2:3 The result is 6方法2
[root@server mnt]# vim Calculator.sh [root@server mnt]# cat Calculator.sh #!/bin/bash read -p "Plese input number 1:" NUM1 read -p "Please input your action:" ACTION read -p "Please input number 2:" NUM2 echo `echo $[$NUM1$ACTION$NUM2]`测试
[root@server mnt]# sh Calculator.sh Plese input number 1:10 Please input your action:/ Please input number 2:3 3