循环命令用于将一个命令或一组命令执行指定的次数,或者一直执行直到满足某个条件为止。在Bashshell中常用的循环语句有,for循环,while循环,until循环

一、For循环语句

1、For循环的语法

forvarinlist

do

commands

done

2、For循环的流程图


3、For循环举例

1)、输入一个文件,判断文件是directory还是file


1234567891011121314151617[root@localhosttest]#cat3.sh#!/bin/shforfilein$1doif[-d"$file"]thenecho"$fileisadirectory"elif[-f"$file"]thenecho"$fileisafile"fidone[root@localhosttest]#sh3.sh/etc/passwd/etc/passwdisafile[root@localhosttest]#sh3.sh/etc/etcisadirectory[root@localhosttest]#


说明:

行3:调用了位置变量$1

行5-11:使用if语句判断$1是文件还是目录


2)、计算一个目录中有多少个文件


123456789[root@localhosttest]#cat4.sh#!/bin/bash#Count=0forFilein/tmp/*;dofile$FileCount=$[$Count+1]doneecho"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]#cat6.sh#!/bin/shSum=0Count=1while[$Count-le100];doletSum+=$CountletCount++doneecho$Sum


如果用户的ID号为偶数,则显示其名称和shell;对所有用户执行此操作;

12345678[root@localhosttest]#cat5.sh#!/bin/shwhilereadLINE;doUid=`echo$LINE|cut-d:-f3`if[$[$Uid%2]-eq0];thenecho$LINE|cut-d:-f1,7fidone</etc/passwd

说明: