shell腳本基礎知識梳理<七>:流程控制 until

until語法shell

until 循環執行一系列命令直至條件爲 true 時中止。bash

until 循環與 while 循環在處理方式上恰好相反。ide

通常 while 循環優於 until 循環,但在某些時候—也只是極少數狀況下,until 循環更加有用。測試

until 語法格式:
until 測試條件
do
指令
donethis

condition 通常爲條件表達式,若是返回值爲 false,則繼續執行循環體內的語句,不然跳出循環。code

實例1:如下實例咱們使用 until 命令來輸出 0 ~ 9 的數字:ip

#!/bin/bashit

a=0io

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

輸出結果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 abab is not a user on this system.

相關文章
相關標籤/搜索