天天看点

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

本文转自 iekegz 51CTO博客,原文链接:http://blog.51cto.com/jacksoner/2045050,如需转载请自行联系原作者