十七週二次課shell
20.10for循環bash
20.11/20.12while循環spa
20.13breakip
20.14continue字符串
20.15exit解析input
20.10for循環it
案例1for循環
#!/bin/bashawk
sum=0監控
for i in `seq 1 100`
do
sum=$[$sum+$i]
echo $i
done
echo $sum
for循環案例2
#!/bin/bash
cd /etc/
for a in `ls /etc/`
do
if [ -d $a ]
then
ls -d $a
fi
done
[root@ip-172-31-21-107 shell]# for a in `seq 1 3` ; do echo $a ; done
1
2
3
[root@ip-172-31-21-107 shell]#
[root@ip-172-31-21-107 shell]# for a in 1 2 3 ; do echo $a ; done
1
2
3
[root@ip-172-31-21-107 shell]#
20.11/20.12while循環
while循環
#!/bin/bash
while :
# 冒號 : 表示死循環的意思,或者1,或者 true都是死循環
do
load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d. -f1`
if [ $load -gt 10 ]
then
/usr/local/sbin/mail.py xxx@163.com "load high" "$load"
fi
sleep 30
#休眠30秒,由於檢查系統負載,不須要一直去檢查,過一會再看
done
[root@ip-172-31-21-107 shell]# sh -x while1.sh
+ :
++ w
++ head -1
++ awk -F 'load average: ' '{print $2}'
++ cut -d. -f1
+ load=0
+ '[' 0 -gt 10 ']'
+ sleep 30
#若想這種腳本不意外的終止,能夠打開screen,在screen跑腳本
#!/bin/bash
while :
do
read -p "Please input a number: " n
if [ -z "$n" ]
then
echo "you need input sth."
continue
#continue 從新回到循環
fi
n1=`echo $n|sed 's/[0-9]//g'`
if [ -n "$n1" ]
then
echo "you just only input numbers."
continue
fi
break
#break 退出循環
done
echo $n
20.13break
break跳出循環
#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i -eq 3 ]
#比較數字,用-eq ;如果比較的是字符串,那須要用 ==
then
break
fi
echo $i
done
echo aaa
[root@ip-172-31-21-107 shell]# sh -x break.sh
++ seq 1 5
+ for i in '`seq 1 5`'
+ echo 1
1
+ '[' 1 -eq 3 ']'
+ echo 1
1
+ for i in '`seq 1 5`'
+ echo 2
2
+ '[' 2 -eq 3 ']'
+ echo 2
2
+ for i in '`seq 1 5`'
+ echo 3
3
+ '[' 3 -eq 3 ']'
+ break
+ echo aaa
aaa
[root@ip-172-31-21-107 shell]
20.14continue
continue結束本次循環
#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i -eq 3 ]
then
continue
fi
echo $i
done
echo aaa
[root@ip-172-31-21-107 shell]# sh -x continue.sh
++ seq 1 5
+ for i in '`seq 1 5`'
+ echo 1
1
+ '[' 1 -eq 3 ']'
+ echo 1
1
+ for i in '`seq 1 5`'
+ echo 2
2
+ '[' 2 -eq 3 ']'
+ echo 2
2
+ for i in '`seq 1 5`'
+ echo 3
3
+ '[' 3 -eq 3 ']'
+ continue
+ for i in '`seq 1 5`'
+ echo 4
4
+ '[' 4 -eq 3 ']'
+ echo 4
4
+ for i in '`seq 1 5`'
+ echo 5
5
+ '[' 5 -eq 3 ']'
+ echo 5
5
+ echo aaa
aaa
[root@ip-172-31-21-107 shell]
20.15exit解析
exit退出整個腳本
#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i -eq 3 ]
then
exit
fi
echo $i
done
echo aaa
[root@ip-172-31-21-107 shell]# sh -x exit.sh
++ seq 1 5
+ for i in '`seq 1 5`'
+ echo 1
1
+ '[' 1 -eq 3 ']'
+ echo 1
1
+ for i in '`seq 1 5`'
+ echo 2
2
+ '[' 2 -eq 3 ']'
+ echo 2
2
+ for i in '`seq 1 5`'
+ echo 3
3
+ '[' 3 -eq 3 ']'
+ exit
[root@ip-172-31-21-107 shell]