39. Until 循环
bash Until 循环在语法和功能上与 while 循环非常相似。
两者之间的唯一区别是until
语句在条件表达式为 false 时执行其代码块,而while
语句在条件表达式为 true 时执行其代码块。
until expression
do
commands #body of the loop
done
until
、do
和done
是关键字- 表达式是任何条件表达式
此 bash Until 循环示例监视日志文件的大小。 一旦日志文件大小达到 2000 字节,它就会创建该日志文件的副本。
$ cat until-monitor.sh
file=/tmp/logfile
until [ $(ls -l $file | awk '{print $5}') -gt 2000 ]
do
echo "Sleeping for next 5 seconds"
sleep 5
done
date=`date +%s`
cp $file "$file-"$date.bak
$ ./until-monitor.sh
Sleeping for next 5 seconds
Sleeping for next 5 second
以下 bash Until 示例用于等待远程计算机启动,然后再通过 ssh 连接到该计算机。 仅当 ping 成功(返回 0)时,until 循环才会结束。
$ cat until-ping-ssh.sh
read -p "Enter IP Address:" ipadd
echo $ipadd
until ping -c 1 $ipadd
do
sleep 60;
done
ssh $ipadd
$./until-ping-ssh.sh
Enter IP Address:192.143.2.10
PING 192.143.2.10 (192.143.2.10) 56(84) bytes of data.
--- 192.143.2.10 ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms
PING 192.143.2.10 (192.143.2.10) 56(84) bytes of data.
64 bytes from 192.143.2.10: icmp_seq=1 ttl=64 time=0.059 ms
--- 192.143.2.10 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.059/0.059/0.059/0.000 ms
[email protected]'s password:
bash Until 循环在命令行中作为等待某些事件发生的一种方式非常有用。