1. 程式人生 > >shell腳本 for循環、break跳出循環、continue結束本次循環

shell腳本 for循環、break跳出循環、continue結束本次循環

輸出 變量名 變量 bin inpu put load cat aaa

20.10 for循環
  • 語法:for 變量名 in 條件; do ...; done
;案例1
[root@qingyun-01 shell]# cat for.sh
#!/bin/bash
sum=0
for i in `seq 1 100`
do
    sum=$[$sum+$i]
done
echo $sum

#輸出的結果
[root@qingyun-01 shell]# sh for.sh 
5050
  • 文件列表循環
[root@qingyun-01 shell]# cat for2.sh 
#!/bin/bash
cd /etc/
for a in `ls /etc/`
do
    if [ -d $a ]
    then
        ls -d $a
    fi
done
#for循環是以空格、回車符作為分割符分割。

20.11-20.12 while循環

  • 語法 while 條件; do ...; done
;案例1
[root@qingyun-01 shell]# cat 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" [email protected]
    fi
    sleep 30
done

;案例2
[root@qingyun-01 shell]# cat while2.sh 
#!/bin/bash
while :
do
  read -p "Please input a number:" n
  if [ -z "$n" ]
  then
      echo "You did not enter the number."
      continue
  fi
  n1=`echo $n|sed ‘s/[0-9]//g‘`
  if [ ! -z "$n1" ]
  then
      echo "You can only enter a pure number."
      continue
  fi
  break
done
echo $n

20.13 break跳出循環

[root@qingyun-01 shell]# cat break.sh 
#!/bin/bash
for i in `seq 1 5`
do
  echo $i
  if [ $i -eq 3 ]
  then
      break
  fi
  echo $i
done
echo aaaaaa

20.14 continue結束本次循環

[root@qingyun-01 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
echo $i

20.15 exit退出整個腳本

[root@qingyun-01 shell]# cat exit.sh 
#!/bin/bash
for i in `seq 1 5`
do
  echo $i
  if [ $i -eq 3 ]
  then
      exit
  fi
  echo $i
done
echo $i

shell腳本 for循環、break跳出循環、continue結束本次循環