until语法

until 循环执行一系列命令直至条件为 true 时停止。

until 循环与 while 循环在处理方式上刚好相反。

一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用。

until 语法格式: until 测试条件 do 指令 done

condition 一般为条件表达式,如果返回值为 false,则继续执行循环体内的语句,否则跳出循环。

实例1:以下实例我们使用 until 命令来输出 0 ~ 9 的数字:

#!/bin/bash

a=0

until [ ! $a -lt 10 ] do echo $a a=expr $a + 1 done

输出结果0 1 2 3 4 5 6 7 8 9

实例 2

#!/bin/bash

#判断ip是否能ping通若不通等待60s read -p "Enter IP Address:" ipadd

until ping -c 1 $ipadd &>/dev/null do echo "${ipadd} ping ........" sleep 60 echo "已等待60s" done

执行结果

[root@localhost shell]# sh until-1.sh Enter IP Address:192.168.1.123 192.168.1.123 ping ........ 已等待60s 192.168.1.123 ping ........ 已等待60s

实例 3

#!/bin/bash

#判断用户是否在系统内 username=$1 if [ $# -lt 1 ] then echo "Usage:'basename $0' <username> [<message>]" exit 1 fi

if grep "^$username:" /etc/passwd > /dev/null then : else echo "$username is not a user on this system." exit 2 fi

until who|grep "$username" > /dev/null do echo "$username is not logged on." sleep 5 done

执行结果

[root@localhost shell]# sh until-2.sh Usage:'basename until-2.sh' <username> [<message>]

[root@localhost shell]# sh until-2.sh ab ab is not a user on this system.