脚本中常用的循环语句
循环命令用于将一个命令或一组命令执行指定的次数,或者一直执行直到满足某个条件为止。在Bashshell中常用的循环语句有,for循环,while循环,until循环
一、For循环语句
1、For循环的语法
forvarinlist
do
commands
done
2、For循环的流程图
3、For循环举例
1)、输入一个文件,判断文件是directory还是file
[root@localhosttest]#cat
3
.sh
#!/bin/sh
for
file
in
$
1
do
if
[-d
"$file"
]
then
echo
"$fileisadirectory"
elif[-f
"$file"
]
then
echo
"$fileisafile"
fi
done
[root@localhosttest]#sh
3
.sh/etc/passwd
/etc/passwd
is
afile
[root@localhosttest]#sh
3
.sh/etc
/etc
is
adirectory
[root@localhosttest]#
说明:
行3:调用了位置变量$1
行5-11:使用if语句判断$1是文件还是目录
2)、计算一个目录中有多少个文件
[root@localhosttest]#cat
4
.sh
#!/bin/bash
#
Count=
0
for
File
in
/tmp/*;
do
file$File
Count=$[$Count+
1
]
done
echo
"Totalfiles:$Count."
说明:
http://t.163.com/event/info/eventId/-2934105915185819762
http://t.163.com/event/info/eventId/7336578789135698864
http://t.163.com/event/info/eventId/-2757900099931402204
http://t.163.com/event/info/eventId/-6022217269862157430
http://t.163.com/event/info/eventId/-6327288559455055957
http://t.163.com/event/info/eventId/-5434619824903743434
http://t.163.com/event/info/eventId/-7296668920759701419
http://t.163.com/event/info/eventId/-6761754697175518719
http://t.163.com/event/info/eventId/2714712527073182328
http://t.163.com/event/info/eventId/-5002856799661246013
http://t.163.com/event/info/eventId/-4996357046007032207
http://t.163.com/event/info/eventId/1105816084476859073
http://t.163.com/event/info/eventId/-8600093788630276814
http://t.163.com/event/info/eventId/8431790839426740003
http://t.163.com/event/info/eventId/-7330955025813744932
http://t.163.com/event/info/eventId/8644906182003528012
http://t.163.com/event/info/eventId/7423718734365387206
http://t.163.com/event/info/eventId/8142539201743089519
http://t.163.com/event/info/eventId/6894078421345426422
http://t.163.com/event/info/eventId/-6211762240931380686
http://t.163.com/event/info/eventId/-8088822526390658491
http://t.163.com/event/info/eventId/5348067141736717459
http://t.163.com/event/info/eventId/1446077859086446713
http://t.163.com/event/info/eventId/-3875504737289263757
http://t.163.com/event/info/eventId/-7305448483219754978
http://t.163.com/event/info/eventId/-6331199466714658720
http://t.163.com/event/info/eventId/-4025232118219909260
行7:每循环一次Count的值+1
二、While循环语句
while命令允许定义要测试的命令,然后只要定义的测试命令返回0状态值,则执行while循环中的语句,否则直接退出
1)、while循环的语法
whiletestcommand
do
otercommand
done
2)、while循环的流程图
3)、while循环举例
计算100以内整数的和
123456789[root@localhosttest]#cat
6
.sh
#!/bin/sh
Sum=
0
Count=
1
while
[$Count-le
100
];
do
letSum+=$Count
letCount++
done
echo$Sum
如果用户的ID号为偶数,则显示其名称和shell;对所有用户执行此操作;
12345678[root@localhosttest]#cat
5
.sh
#!/bin/sh
while
readLINE;
do
Uid=`echo$LINE|cut-d:-f3`
if
[$[$Uid%
2
]-eq
0
];then
echo$LINE|cut-d:-f1,
7
fi
done</etc/passwd
说明:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。