循环命令用于将一个命令或一组命令执行指定的次数,或者一直执行直到知足某个条件为止。在Bash shell中经常使用的循环语句有,for循环,while循环,until循环shell
1、For循环语句bash
一、For循环的语法
ide
for var in listoop
do 测试
commands spa
doneblog
二、For循环的流程图
hadoop
三、For循环举例get
1)、输入一个文件,判断文件是directory仍是fileit
[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)、计算一个目录中有多少个文件
[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."
说明:
行7:每循环一次Count的值+1
2、While循环语句
while命令容许定义要测试的命令,而后只要定义的测试命令返回0状态值,则执行while循环中的语句,不然直接退出
1)、while循环的语法
while test command
do
oter command
done
2)、while循环的流程图
3)、while循环举例
计算100之内整数的和
[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;对全部用户执行此操做;
[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
说明:
行3,8:将passwd中的每一行给变量LINE赋值(因为while能读到 $LINE的值,因此判断为 真,状态返回值为0)
行4,5,6:取出$LINE中用户的UID并判断UID是不是偶数,若是是偶数则显示其用户名和 shell
3、Until循环语句
Until命令容许定义要测试的命令,而后只要定义的测试命令返回非0状态值,则执行unitl循环中的语句,不然直接退出(unitl和while恰好相反)
1)、Until循环语句的语法
until test command
do
oter command
done
2)、Until循环的流程图
3)Until循环举例
计算100之内整数的和
[root@localhost test]# cat 6.sh #!/bin/sh Sum=0 Count=1 until [ $Count -gt 100 ]; do let Sum+=$Count let Count++ done echo $Sum
每隔5秒查看hadoop用户是否登陆,若是登陆,显示其登陆并退出;不然,显示当前时间,并说 明hadoop还没有登陆:
who | grep "^TOM" &> /dev/null RetVal=$? until [ $RetVal -eq 0 ]; do date sleep 5 who | grep "^TOM" &> /dev/null RetVal=$? done echo "TOM is here."
说明:
行1,2:查看TOM用户是否登陆,而后输出状态码
行3:若是状态返回值等于0则不执行下面的脚本。
行4,5:显示时间并设置sleep 5秒
行6,7:再次检查用户TOM是否登录