for 循環
web
範圍的符號用 `` bash
`seq 範圍` app
1.測試腳本:(1加到100)內容:ide
結果:測試
2.遍歷/etc/下的目錄:spa
內容:命令行
結果:orm
for i in `seq 1 3` == for i 1 2 3
ip
for循環會以空格或回車做爲分隔符字符串
例如:/tmp/下有三個文件 1.txt、2.txt和3 4.txt(3 4.txt是一個文件,3和4之間有空格)
當在命令行中執行:for i in `ls /tmp/` do echo $i ;done
結果則會出現四個文件這樣的顯示1.txt、 2.txt、3和4.txt(這是3 4.txt是一個文件卻由於空格拆分紅兩個)
while循環
1.格式:
while 條件 ;do ...;done
如 (1)while : (死循環) do ;done
(2)while true == while 1 ;do...;done
2.案例當系統負載大於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" asldkfls@11.com
(或者:/usr/lib/zabbix/alertscripts/mail.py 15521787110@163.com "load is high: $load")
fi
sleep 30 //添加時間間斷,沒30秒查一次
done
( load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d. -f1`
過濾所要所要字符。|sed 's/ //' 把過濾字符前的空格去除
)
3.案例:判斷輸入的內容是否爲數字
#!/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跳出循環
當在腳本中的for或者while的循環中都是能夠的。使用break,當條件
知足時就會直接跳出本層的循環(就是跳出使用了break這層的循環)
執行結果
在使用if做判斷時,要在條件範圍在[ ]中的左右都要空一格,不然會有
語法錯誤。
continue結束本次循環
!!忽略continue之下的代碼,直接進行下一次循環
continue 是僅僅的結束知足條件的那一次過程,以後的命令也是會執行的
執行結果:
exit退出整個腳本
當整個流程運行命令,遇到exit時,直接退出腳本。
執行結果: