循环命令用于将一个命令或一组命令执行指定的次数,或者一直执行直到满足某个条件为止。在Bash shell中常用的循环语句有,for循环,while循环,until循环
一、For循环语句
1、For循环的语法
for var in list
do
commands
done
2、For循环的流程图
3、For循环举例
1)、输入一个文件,判断文件是directory还是file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | [root@localhost test]# cat 3 .sh #!/bin/sh for file in $ 1 do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi done [root@localhost test]# sh 3 .sh /etc/passwd /etc/passwd is a file [root@localhost test]# sh 3 .sh /etc /etc is a directory [root@localhost test]# |
说明:
行3:调用了位置变量$1
行5-11:使用if语句判断$1是文件还是目录
2)、计算一个目录中有多少个文件
1 2 3 4 5 6 7 8 9 | [root@localhost test]# cat 4 .sh #!/bin/bash # Count= 0 for File in /tmp/*; do
file $File
Count=$[$Count+ 1 ] done echo "Total files: $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循环的语法
while test command
do
oter command
done
2)、while循环的流程图
3)、while循环举例
计算100以内整数的和
1 2 3 4 5 6 7 8 9 | [root@localhost test]# cat 6 .sh #!/bin/sh Sum= 0 Count= 1 while [ $Count -le 100 ]; do
let Sum+=$Count
let Count++ done echo $Sum |
如果用户的ID号为偶数,则显示其名称和shell;对所有用户执行此操作;
1 2 3 4 5 6 7 8 | [root@localhost test]# cat 5 .sh #!/bin/sh while read LINE; do
Uid=`echo $LINE | cut -d: -f3`
if [ $[$Uid% 2 ] -eq 0 ]; then
echo $LINE | cut -d: -f1, 7
fi done < /etc/passwd |
说明:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。