如何在 Linux 的 bash 中永远循环 | Linux 中国
https://linux.cn/article-12368-1.html
作者:Sandra Henry-stocker
译者:geekpi
在 Linux 中有很多永远循环(或直到你决定停止)的方法,你可以在命令行或脚本中执行此操作。
使用 while
最简单的永远循环之一是使用 while 命令,后面跟上条件 true。你不必使用诸如 while [ 1 -eq 1 ] 之类的逻辑或类似的测试。 while true 测试表示循环将一直运行,直到你使用
CTRL-C
停止循环、关闭终端窗口或注销为止。这是一个例子:$ whiletrue
>do
>echoKeep running
>sleep3
>done
Keep running
Keep running
Keep running
^C
$ while:
>do
>echoKeep running
>sleep3
>done
Keep running
Keep running
^C
如果你在脚本中插入了无限循环,并想提醒使用它的人如何退出脚本,那么可以使用
echo
命令添加提示:while:
do
echoKeep running
echo"Press CTRL+C to exit"
sleep1
done
使用 for
for 命令还提供了一种永远循环的简便方法。虽然不如 while true 明显,但语法相当简单。你只需要在有界循环中替换参数即可,它通常类似于 “c 从等于 1 开始递增,直到 5”:
$ for(( c=1; c<=5; c++))
不指定任何参数的情况下:
$ for((;;))
没有起始值、增量或退出测试,此循环将永远运行或被强制停止:
$ for((;;))
>do
>echoKeep running
>echo“Press CTRL+C to exit”
>sleep2
>done
Keep your spirits up
Keep your spirits up
Keep your spirits up
为什么要永远循环?
在现实中,你不会想永远循环下去,但一直运行直到想要回家、工作完成或者遇到问题才退出并不罕见。任何构造为无限循环的循环都可以设置为根据各种情况退出。
该脚本将一直处理数据直到下午 5 点,或者说检查发现第一次超过 5 点的时间:
#!/bin/bash
whiletrue
do
if[`date +%H`-ge 17];then
exit#exitscript
fi
echo keep running
~/bin/process_data #do some work
done
如果要退出循环而不是退出脚本,请使用
break
命令而不是 exit
。#!/bin/bash
whiletrue
do
if[`date +%H`-ge 17];then
break#exit loop
fi
echo keep running
~/bin/process_data
done
… run other commands here …
总结
永远循环很容易。指定要停止循环的条件却需要花费一些额外的精力。
关键词
中国
脚本中
方法
语法
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。