38. While 循环
bash shell 提供的另一个迭代语句是 while 语句。
while expression
do
commands
done
while
、do
、done
是关键字- 表达式是返回标量值的任何表达式
- 当提供的条件表达式为真时,执行
do
和done
之间的命令。
此示例从 stdin
(键盘)读取数据并将其写入文件。 需要 EOF (Ctrl-Z
) 来终止输入:
$ cat while-writefile.sh
#! /bin/bash
echo -e "Enter absolute path of the file you want to create"
read file
while read line
do
echo $line >> $file
done
Ctrl-z
表示您键入Ctrl-Z
来终止输入。
$ sh while-writefile.sh
Enter absolute path of the file you want to create
/tmp/a
while
for
until
Ctrl-Z
$ cat /tmp/a
while
for
until
在前面的示例中,bash 从用户处读取文件名 /tmp/a
,然后从 stdin 读取数据行,直到看到 EOF
,将每一行附加到 filename
指定的文件中。
echo
命令输出的 Bash 重定向用于附加行。
EOF
终止循环,因为读取失败(即返回非零值)。
下一个示例将 bash 数据从文件写入到 stdout(类似于cat
)。
在此示例中,输入仍然取自 stdin,但使用了 bash 重定向,以便 stdin 来自指定文件而不是来自键盘。
请注意这两个示例如何利用非常强大的重定向技术,我们将在后面的部分中详细讨论这一技术。
读取文件并将其回显到标准输出:
$ cat while-read.sh
#! /bin/bash
echo -e "Enter absolute path of the file name you want to read"
read file
exec <$file # redirects stdin to a file
while read line
do
echo $line
done
/tmp/a
。
$ ./while-read.sh Enter absolute path of the file name you want to read /tmp/a while for until
在此示例中,bash 获取要从 stdin(键盘)读取的文件名,然后使用exec
重定向 stdin 到文件,从文件而不是键盘获取进一步的输入。
与前面的示例一样,当 EOF
发生时,读取命令失败,从而终止循环。
使用 Bash While 进行无限循环
您可以使用 while true
创建无限循环,就像前面演示的for (;;)
语法一样。
下一个示例使用无限循环来测试服务器是否已启动并正在运行。sleep
命令用于定期(在本例中为 60 秒)进行 ping 测试。
该脚本将使用命令nohup
或不挂起来执行,并在命令行末尾加上 &
,以便它与当前 shell 分离。
这样,只要系统仍在运行,即使您注销登录,脚本也会继续运行。
示例:每 60 秒测试一次 ip-address 192.168.100.10 的服务器,如果失败则显示一条消息。
$ cat until-loop.sh
IP=192.168.101.10
while true
do
ping -c 2 $IP > /dev/null
if [ $? -ne 0 ]; then
echo "Server $IP is not responding"
fi
sleep 2
done
$ nohup until-loop.sh &