for循環
語法:for 變量名 in 條件 ; do done;
案例一:
計算1-100所有數字的和。
腳本:
#!/bin/bash
sum=0
for i in `seq 1 100`
do
sum=$[$sum+$i]
done
echo $sum
結果:
[root@congji ~]# sh 1-100.sh
5050
案例二:
列出/etc/sysconfig下所有子目錄,並且使用ls -d命令查看。
腳本:
#/bin/bash
cd /etc/sysconfig
for i in `ls /etc/sysconfig`
do
if [ -d $i ]
then
ls -d $i
fi
done
結果:
[root@congji ~]# sh syscon.sh
cbq
console
modules
network-scripts
for循環有一個值得注意的地方:
案例3:
我們創建幾個文件,用for循環來ls他們。
[root@congji shili]# ll
總用量 0
-rw-r--r-- 1 root root 0 1月 16 21:16 1.txt
-rw-r--r-- 1 root root 0 1月 16 21:16 2.txt
-rw-r--r-- 1 root root 0 1月 16 21:17 3 4.txt
[root@congji shili]# for i in `ls ./`;do echo $i ;done
1.txt
2.txt
3
4.txt
所以寫腳本的時候要注意
while循環
語法 while條件;do...;done
案例1:寫一個腳本來監控系統負載,當系統負載大於10時,發郵箱警告。
腳本:
#/bin/bash
while :
do
load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d. -f1`
if [ $load -gt 10 ]
then
/usr/local/sbin/mail.py [email protected] "load high" "$load"
fi
sleep 30
done
運行結果:
[root@congji shell]# sh -x while.sh
+ :
++ w
++ head -1
++ awk -F 'load average: ' '{print $2}'
++ cut -d. -f1
+ load=0
+ '[' 0 -gt 10 ']'
+ sleep 30
案例二:
類似於之前寫過的for循環的腳本,輸入一個數字,如果不是數字返回一個字符串,如果輸入爲空返回一個字符串,如果是數字返回。
在看腳本之前,我們需要知道continue和break的意思。
continue是繼續的意思,也就是當運行結果不滿足條件時,在從頭循環一遍。
break是跳出循環的意思。
腳本:
#/bin/bash
while :
do
read -p "please input a number: " n
if [ -z "$n" ]
then
echo "你需要輸入東西."
continue
fi
n1=`echo $n|sed 's/[0-9]//g'`
if [ ! -z "$n1" ]
then
echo "你只能輸入一個純數字."
continue
fi
break
done
echo $n
運行結果:
[root@congji shell]# sh while2.sh
please input a number: 1d
你只能輸入一個純數字.
please input a number:
你需要輸入東西.
please input a number: 1
1
break
break在while循環中,我們提到了,這裏來寫一個腳本,加深印象
如果輸入的數字小於等於3,則返回數字,如果輸入的數字大於3,則返回aaaa
腳本:
#/bin/bash
read -p "please input a number: " i
if [ $i -lt 3 ]
then
echo $i
break
else
echo aaaa
fi
運行結果:
[root@congji shell]# sh break.sh
please input a number: 1
1
[root@congji shell]# sh break.sh
please input a number: 5
aaaa
continue結束本次循環,而break是跳出循環,要分清楚
[root@congji shell]# cat continue.sh
#/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i -eq 3 ]
then
continue
fi
echo $i
done
[root@congji shell]# sh continue.sh
1
1
2
2
3
4
4
5
5
[root@congji shell]# cat break.sh
#/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i == 3 ]
then
break
fi
echo $i
done
[root@congji shell]# sh break.sh
1
1
2
2
3
對比兩個腳本我們可以發現,break相當於跳出循環,結束。而continue相當於結束本次循環,開始新的循環,