for循環、while循環、break跳出循環、continue結束本次循環、exit退出腳本
阿新 • • 發佈:2018-07-16
ber 系統負載 bash 一個 輸入 numbers etc 判斷 for循環 for循環
w是系統負載的命令
head -1 取命令結果的第一行
|awk -F ‘load average: ‘ ‘{print $2} 指定分隔符為load average,取第二段
cut -d. -f1 指定分隔符為 “ . ”,取第1段
?語法:for 變量名 in 條件; do …; done
示例
計算1到100所有數字的和
#!/bin/bash
sum=0
for i in `seq 1 100`
do
sum=$[$sum+$i]
done
echo $sum
列出etc目錄下的所有目錄
#!/bin/bash
cd /etc/
for a in `ls /etc/`
do
if [ -d $a ]
then
echo $a
ls $a
fi
done
while循環
語法 while 條件; do … ; done
示例
每隔30秒檢查系統的負載,如果大於10則發一封郵件
#!/bin/bash
while true
do
load=`w|head -1|awk -F ‘load average: ‘ ‘{print $2}‘|cut -d. -f1`
if [ $load -gt 10 ]
then
/root/shell/mail.py [email protected] "load high" "$load"
fi
sleep 30
done
while true 判斷是否為真,這樣可以寫一個死循環的腳本
w|head -1|awk -F ‘load average: ‘ ‘{print $2}‘|cut -d. -f1
head -1 取命令結果的第一行
|awk -F ‘load average: ‘ ‘{print $2} 指定分隔符為load average,取第二段
cut -d. -f1 指定分隔符為 “ . ”,取第1段
if [ $load -gt -1 ] 判斷load是否大於10,如果大於10那麽執行下面的語句,這是一個發郵件的腳本
sleep 30 執行後休眠30秒再執行
讓用戶輸入一個數字,直到正確為止
#!/bin/bash while : do read -p "Please input a number: " n if [ -z "$n" ] then echo "you need input sth." continue fi n1=`echo $n|sed ‘s/[0-9]//g‘` if [ -n "$n1" ] then echo "you just only input numbers." continue fi break done echo $n
break跳出循環與contiue結束本次循環、exit退出腳本
輸入一個數字,
當為正確的數字時break跳出循環
#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i -eq 3 ]
then
break
fi
echo $i
done
echo ok
腳本運行結果
[root@yang shell]# sh br.sh
1
1
2
2
3
ok
continue結束本次循環
!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i -eq 3 ]
then
continue
fi
echo $i
done
echo ok
腳本運行結果
[root@yang shell]# sh co.sh
1
1
2
2
3
4
4
5
5
ok
exit退出腳本
#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i -eq 3 ]
then
exit
fi
echo $i
done
echo ok
腳本運行結果
[root@yang shell]# sh ex.sh
1
1
2
2
3
for循環、while循環、break跳出循環、continue結束本次循環、exit退出腳本