hellopasswd
while循环
- 语法while条件;do...;done
- 案例(每隔半分钟检查系统负载,当系统负载大于10就发一封邮件) #!/bin/bash while: do load=
w | head -1 | awk -F 'load average:''{print $2}' | cut -d . -f1
if [ $load -gt 10 ] then top | mail -s "load is high:$load" fi sleep 30 done
[root@localhost shell]# w 03:32:16 up 11:45, 1 user, load average: 0.00, 0.01, 0.05USER TTY LOGIN@ IDLE JCPU PCPU WHATroot pts/0 03:27 0.00s 0.06s 0.00s w[root@localhost shell]# w | head -1 | awk -F 'load average: ' '{print $2}'0.00, 0.01, 0.05[root@localhost shell]# w | head -1 | awk -F 'load average: ' '{print $2}' | cut -d. -f10[root@localhost shell]# uptime 03:32:20 up 11:45, 1 user, load average: 0.00, 0.01, 0.05[root@localhost shell]# uptime | head -1 | awk -F 'load average: ' '{print $2}'0.00, 0.01, 0.05[root@localhost shell]# uptime | head -1 | awk -F 'load average: ' '{print $2}' | cut -d. -f10
去掉空格
[root@localhost shell]# uptime | head -1 | awk -F 'load average:' '{print $2}' | cut -d. -f1 0[root@localhost shell]# uptime | head -1 | awk -F 'load average: ' '{print $2}' | cut -d. -f10[root@localhost shell]# uptime | head -1 | awk -F 'load average:' '{print $2}' | cut -d. -f1 | sed 's/ //'0
[root@localhost ~]# cd shell/[root@localhost shell]# vi 1.sh 1 #!/bin/bash 2 while : 3 do 4 load=`w | head -1 | awk -F 'load average: ' '{print $2}' | cut -d. -f1` 5 if [ $load -gt 10 ] 6 then 7 /usr/local/sbin/mail.py hellopasswd@163.com "load high" "$load" 8 fi 9 sleep 30 10 done
while :表示为真,与while 1和while true作用相同
[root@localhost shell]# sh -x 1.sh + :++ w++ head -1++ awk -F 'load average: ' '{print $2}'++ cut -d. -f1+ load=0+ '[' 0 -gt 10 ']'+ sleep 30
每30s运行一次
- while循环案例 #!/bin/bash while : do read -p "please input a number:"n if [ -z $n ] then echo "You need input something" continue fi n1=
echo $n | sed 's/[0-9]//g'
if [ ! -z $n1 ] then echo "You must input a number" continue fi break done echo $n
1 #!/bin/bash 2 while : 3 do 4 read -p "Please input a number:" n 5 if [ -z "$n" ] 6 then 7 echo "You need input something" 8 continue 9 fi 10 n1=`echo $n | sed 's/[0-9]//g'` 11 if [ ! -z "$n1" ] 12 then 13 echo "You must input a number" 14 continue 15 fi 16 break 17 done 18 echo $n
[root@localhost shell]# sh -x 1.sh + :+ read -p 'Please input a number:' nPlease input a number:+ '[' -z '' ']'+ echo 'You need input something'You need input something+ continue+ :+ read -p 'Please input a number:' nPlease input a number:a+ '[' -z a ']'++ echo a++ sed 's/[0-9]//g'+ n1=a+ '[' '!' -z a ']'+ echo 'You must input a number'You must input a number+ continue+ :+ read -p 'Please input a number:' nPlease input a number:1+ '[' -z 1 ']'++ echo 1++ sed 's/[0-9]//g'+ n1=+ '[' '!' -z '' ']'+ break+ echo 11[root@localhost shell]# sh 1.sh Please input a number:You need input somethingPlease input a number:aYou must input a numberPlease input a number:11
修改于 180212