天天看點

for循環、while循環、break跳出循環、continue結束本次循環、exit退出整個腳本

1、求1加到100的數字的合是多少

2、循環目錄清單

[root@centos7 shell]# vi for.sh

#!/bin/bash

dir=/usr/local/sbin/

for a in <code>ls $dir</code>

do

if [ -d $a ]

then

echo $a

ls $a

fi

done

echo "No directory file!"

格式: while 條件;do…;done

1、當系統負載大于10的時候,發送郵件,每隔30秒執行一次。

while : 表示真命題,相當于while true

while :

load=<code>w|head -1 |awk -F 'load average:' '{print $2}' |cut -d . -f1</code>

if [ $load -gt 10 ]

top |mail -s "load is high: $load" [email protected]

sleep 30

2、

read -p 'please input a num:' n

if [ -z "$n" ];then

echo "please input num"

continue

echo $n

n1=<code>echo $n|sed 's#[0-9]##g'</code>

if [ -n "$n1" ];then

exit 2

else

break

#continue:中斷本次while循環後重新開始;

#break:表示跳出本層循環,即該while循環結束

1、當等于3就跳出循環

for i in <code>seq 1 5</code>

echo "$i"

if [ $i -eq 3 ]

echo "Finished!"

結果:

[root@centos7 shell]# sh break.sh 

1

2

3

Finished!

1、當等于3了就跳過繼續執行,本次循環結束,開始下一個循環

4

5

1、當等于3就退出整個腳本

exit

1、

echo "please input 1.w 2.top 3.free 4.quit"

select com in w top free quit

case $com in

w)

w

;;

top)

top

free)

free

*)

esac

執行結果:

[root@centos7 shell]# sh select.sh 

please input 1.w 2.top 3.free 4.quit

1) w

2) top

3) free

4) quit

本文轉自方向對了,就不怕路遠了!51CTO部落格,原文連結:http://blog.51cto.com/jacksoner/2045050 ,如需轉載請自行聯系原作者