for循环
一般格式:
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
写成一行:
for var in item1 item2 ... itemN; do command1; command2… done;
eg:
需求:求1到100数字的和。
[root@dl-001 sbin]# vim sum.sh
#!/bin/bash
sum=0
for i in `seq 1 5`
do
sum=$[sum+$i]
done
echo "$sum"
[root@localhost sbin]# sh sum.sh
15
需求:文件列表循环
[root@dl-001 sbin]# vim for.sh
#!/bin/bash
dir=/usr/local/sbin/
for a in `ls $dir`
do
if [ -d $a ]
then
echo $a
ls $a
fi
done
echo "No directory file!"
[root@dl-001 sbin]# sh -x for.sh
+ dir=/usr/local/sbin/
++ ls /usr/local/sbin/
+ for a in '`ls $dir`'
+ '[' -d datefile.sh ']'
+ for a in '`ls $dir`'
+ '[' -d filetar.sh ']'
+ for a in '`ls $dir`'
+ '[' -d for.sh ']'
+ for a in '`ls $dir`'
+ '[' -d if2.sh ']'
+ for a in '`ls $dir`'
+ '[' -d sum.sh ']'
+ echo 'No directory file!'
No directory file!
for——分隔符
[root@dl-001 dd]# touch 1.txt
[root@dl-001 dd]# touch 1\ 2.txt //这里的\是转义的意思,创建的是一个 1 2.txt文件
[root@dl-001 dd]# ls
1 2.txt 1.txt
[root@dl-001 dd]# for i in `ls ./` ; do echo $i ; done
1
2.txt
1.txt //可见for循环已经把1 2.txt 循环分割成了1 , 2.txt
注意:for默认情况下把空格或换行符(回车)作为分隔符。
while循环
普通格式:
while condition
do
command
done
简化格式:
while 条件;do…;done
无限循环语法格式:
while :
do
command
done
eg:
需求:当系统负载大于10的时候,发送邮件,每隔30秒执行一次。
[root@dl-001 shell]# vim 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" abc@111.com
fi
sleep 30
done
#while “:”表示死循环,也可以写成while true,意思是“真”
#Attention:awk -F 'load average: '此处指定'load average: '为分隔符,注意冒号后面的空格
#如果不加该空格,过滤出来的结果会带空格,需要在此将空格过滤掉
[root@dl-001 shell]# sh -x while.sh
+ :
++ head -1
++ awk -F 'load average: ' '{print $2}'
++ cut -d. -f1
++ w
+ load=0
+ '[' 0 -gt 10 ']'
+ sleep 30
.
.
.
说明:如果不手动停止该脚本,它会一直循环执行(按Ctrl+c结束),实际环境中配合screen使用。
需求:交互模式下,用户输入一个字符,检测该字符是否符合条件,如:空、非数字、数字。分别对字符做出判断,然后做出不同的回应。
[root@dl-001 sbin]# vim while2.sh
#!/bin/bash
while true
do
read -p "Please input a number:" n
if [ -z "$n" ]
then
echo "You need input some characters!"
continue
fi
n1=`echo $n|sed 's/[-0-9]//g'`
if [ -n "$n1" ]
then
echo "The character must be a number!"
continue
fi
break
done
echo $n
#continue:中断本次while循环后重新开始;
#break:表示跳出本层循环,即该while循环结束
[root@dl-001 shell]# sh while2.sh
Please input a number:
You need input a character!
Please input a number:eee333
The character must be a number!
Please input a number:3
3
break 跳出循环
eg:
[root@dl-001 sbin]# 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 "Finished!"
[root@dl-001 sbin]# sh break.sh
1
1
2
2
3
Finished!
即,跳出while循环,继续执行循坏之外的命令。