20.10 for循环
案例1
1. 编写for循环脚本:计算1到100所有数字和:
[root@hao-01 ~]# 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脚本:
[root@hao-01 ~]# sh for1.sh
案例2
1. 文件列表循环(常用)
[root@hao-01 ~]# 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脚本:
[root@hao-01 ~]# sh -x for2.sh
[root@hao-01 ~]# for i in `ls ./`; do echo $i ; done
20.11 while循环(上)
语法: while 条件; do 内容… ; done
1. 每隔30秒检查系统负载,当负载达到10,发一份邮件!
[root@hao-01 ~]# 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 zhuneianxiang@163.com "load load" "$load"
fi
sleep 30
done
2. 执行while1.sh脚本:
[root@hao-01 ~]# sh -x while1.sh
20.12 while循环(下)
1. 让用户不断的输入纯数字,才停止换算!
[root@hao-01 ~]# 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脚本:
[root@hao-01 ~]# sh -x while2.sh
20.13 break跳出循环
1. break跳出循环:
[root@hao-01 ~]# 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脚本:
[root@hao-01 ~]# sh -x break.sh
[root@hao-01 ~]# sh break.sh
20.14 continue结束本次循环
1. continue结束本次循环:
[root@hao-01 ~]# 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脚本:
[root@hao-01 ~]# sh continue
20.15 exit退出整个脚本
1. exit直接退出整个脚本:
[root@hao-01 ~]# 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脚本:
[root@hao-01 ~]# sh exit.sh