20.10 for循环;20.11 while循环(上);20.12 while循环(下);20.13 break跳出循环;20.14 ;20.15

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了20.10 for循环;20.11 while循环(上);20.12 while循环(下);20.13 break跳出循环;20.14 ;20.15相关的知识,希望对你有一定的参考价值。

20.10 for循环

案例1

1. 编写for循环脚本:计算1100所有数字

[[email protected] ~]# vi for1.sh

添加内容:

#!/bin/bash

sum=0

for i in `seq 1 100`

do

echo "$sum + $i"

sum=$[$sum+$i]

echo $sum

done

echo $sum

2. 执行for1.sh脚本:

[[email protected] ~]# sh for1.sh

案例2

1. 文件列表循环(常用)

[[email protected] ~]# vim for2.sh

添加内容:

#!/bin/bash

cd /etc/

for a in ls /etc/

do

if [ -d $a ]

then

echo $a

ls $a

fi

done

2. 执行for2.sh脚本:

[[email protected] ~]# sh -x for2.sh


[[email protected] ~]# for i in `ls ./`; do echo $i ; done

20.11 while循环(上)

语法: while 条件; do 内容… ; done

1. 每隔30秒检查系统负载,当负载达到10,发一份邮件!

[[email protected] ~]# vim while1.sh

添加内容:

#!/bin/bash

while true

do

    load=`w|head -1|awk -F ‘load average: ‘ ‘{print $2}‘|cut -d. -f1`

    if [ $load -gt 10 ]

    then

         /usr/local/sbin/mail.py [email protected] "load load" "$load"

    fi

    sleep 30

done

技术分享

2. 执行while1.sh脚本:

[[email protected] ~]# sh -x while1.sh

20.12 while循环(下)

1. 让用户不断的输入纯数字,才停止换算!

[[email protected] ~]# vim while2.sh

添加内容:

#!/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

2. 执行while2.sh脚本:

[[email protected] ~]# sh -x while2.sh

20.13 break跳出循环

1. break跳出循环:

[[email protected] ~]# 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 aaaaa

2. 执行break.sh脚本:

[[email protected] ~]# sh -x break.sh

[[email protected] ~]# sh break.sh

20.14 continue结束本次循环

1. continue结束本次循环

[[email protected] ~]# vim continue.sh

添加内容:

#!/bin/bash

for i in `seq 1 5`

do

echo $i

if [ $i -eq 3 ]

then

continue

fi

echo $i

done

echo aaaaa

2. 执行continue.sh脚本:

[[email protected] ~]# sh continue

20.15 exit退出整个脚本

1. exit直接退出整个脚本:

[[email protected] ~]# vim exit.sh

添加内容:

#!/bin/bash

for i in `seq 1 5`

do

echo $i

if [ $i -eq 3 ]

then

exit

fi

echo $i

done

echo aaaaa

2. 执行exit.sh脚本:

[[email protected] ~]# sh exit.sh

 

本文出自 “主内安详” 博客,请务必保留此出处http://zhuneianxiang.blog.51cto.com/11621252/1966370

以上是关于20.10 for循环;20.11 while循环(上);20.12 while循环(下);20.13 break跳出循环;20.14 ;20.15的主要内容,如果未能解决你的问题,请参考以下文章

20.10 for循环;20.11 while循环(上);20.12 while循环(下);20.13 break跳出循环;20.14 ;20.15

20.10 for循环 20.11/20.12 while循环 20.13 break跳出循环 20.14 continue结束本次循环 20.15 exit退出整个脚本

2018-7-13

2018.4.19 17周2次课

for循环while循环continuebreakexit解析select用法

2018-4-19 17周2次课 for循环while循环breakcontinueexit