for循環,while循環,break跳出循環

for循環

一般格式:

for var in item1 item2 ... itemN
do
    command1
    command2
    ...
    commandN
done

寫成一行:

for var in item1 item2 ... itemN; do command1; command2… done;

eg:

需求:求1到100數字的和。

[root@dl-001 sbin]# vim sum.sh
#!/bin/bash
sum=0
for i in `seq 1 5`
do
  sum=$[sum+$i]
done
echo "$sum"

[root@localhost sbin]# sh sum.sh 
15

需求:文件列表循環

[root@dl-001 sbin]# vim for.sh
#!/bin/bash
dir=/usr/local/sbin/
for a in `ls $dir`
do
    if [ -d $a ]
    then
        echo $a
        ls $a
    fi
done
echo "No directory file!"

[root@dl-001 sbin]# sh -x for.sh 
+ dir=/usr/local/sbin/
++ ls /usr/local/sbin/
+ for a in '`ls $dir`'
+ '[' -d datefile.sh ']'
+ for a in '`ls $dir`'
+ '[' -d filetar.sh ']'
+ for a in '`ls $dir`'
+ '[' -d for.sh ']'
+ for a in '`ls $dir`'
+ '[' -d if2.sh ']'
+ for a in '`ls $dir`'
+ '[' -d sum.sh ']'
+ echo 'No directory file!'
No directory file!

for——分隔符

[root@dl-001 dd]# touch 1.txt
[root@dl-001 dd]# touch 1\ 2.txt        //這裏的\是轉義的意思,創建的是一個 1 2.txt文件
[root@dl-001 dd]# ls
1 2.txt  1.txt
[root@dl-001 dd]# for i in `ls ./` ; do echo $i ; done
1
2.txt
1.txt        //可見for循環已經把1 2.txt 循環分割成了1  ,   2.txt

注意:for默認情況下把空格或換行符(回車)作爲分隔符。


while循環

普通格式:

while condition
do
    command
done

簡化格式:

while 條件;do…;done

無限循環語法格式:

while :
do
    command
done

eg:

需求:當系統負載大於10的時候,發送郵件,每隔30秒執行一次。

[root@dl-001 shell]# vim while.sh
#!/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" abc@111.com
  fi
   sleep 30
done
#while “:”表示死循環,也可以寫成while true,意思是“真”

#Attention:awk -F 'load average: '此處指定'load average: '爲分隔符,注意冒號後面的空格
#如果不加該空格,過濾出來的結果會帶空格,需要在此將空格過濾掉  


[root@dl-001 shell]# sh -x while.sh 
+ :
++ head -1
++ awk -F 'load average: ' '{print $2}'
++ cut -d. -f1
++ w
+ load=0
+ '[' 0 -gt 10 ']'
+ sleep 30
.
.
.

說明:如果不手動停止該腳本,它會一直循環執行(按Ctrl+c結束),實際環境中配合screen使用。

需求:交互模式下,用戶輸入一個字符,檢測該字符是否符合條件,如:空、非數字、數字。分別對字符做出判斷,然後做出不同的迴應。

[root@dl-001 sbin]# vim while2.sh
#!/bin/bash
while true
do
  read -p "Please input a number:" n
  if [ -z "$n" ]
  then 
      echo "You need input some characters!"
      continue
  fi
  n1=`echo $n|sed 's/[-0-9]//g'`
  if [ -n "$n1" ]
  then
      echo "The character must be a number!"
      continue
  fi
  break
done
echo $n
#continue:中斷本次while循環後重新開始;
#break:表示跳出本層循環,即該while循環結束

[root@dl-001 shell]# sh while2.sh 
Please input a number: 
You need input a character!
Please input a number:eee333
The character must be a number!
Please input a number:3
3

break 跳出循環

eg:

[root@dl-001 sbin]# vim break.sh
#!/bin/bash
for i in `seq 1 5`
do
  echo "$i"
  if [ $i -eq 3 ]
  then
  break
  fi
  echo "$i"
done
echo "Finished!"


[root@dl-001 sbin]# sh break.sh 
1
1
2
2
3
Finished!

即,跳出while循環,繼續執行循壞之外的命令。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章