âšď¸ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.1 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://www.networkworld.com/article/3600146/how-to-loop-forever-in-bash.html |
| Last Crawled | 2026-04-04 03:45:50 (2 days ago) |
| First Indexed | 2024-11-06 19:18:59 (1 year ago) |
| HTTP Status Code | 200 |
| Meta Title | How to loop forever in bash | Network World |
| Meta Description | Looping forever is easy if you know what commands you want to run repeatedly and the conditions under which you want them to stop running. |
| Meta Canonical | null |
| Boilerpipe Text | There are several ways to loop âforeverâ on Linux commands. In practice, this means only until you decide to stop looping. You might do this while typing commands on the command line, or, more likely, within your scripts. Itâs quite easy. This post provides some examples of how to do this.
The
for
 andÂ
while
 commands will provide what you need. There are only a few things you have to keep in mind with respect to syntax and techniques.
Using while
One of the easiest forever-loops involves using theÂ
while
 command followed by the condition âtrueâ. You donât have to bother with logic like while [ 1 -eq 1 ] or similar tests. TheÂ
while true
 test means the loop will run until you stop it with CTRL-C, close the terminal window, log out, or restart the system. After all, true is always true. Hereâs an example:
$ while true
> do
> echo Keep running
> sleep 3
> done
Keep running
Keep running
Keep running
^C
The command in the example above will continue running, echo âKeep runningâ after every three-second break. Try âwhile falseâ and it wonât loop even once!
$ while false
> do
> echo Keep running
> sleep 3
> done
$
You can do the same thing with a âwhile :â test if you prefer. The key here is that the colon always yields success. Like âwhile trueâ, this test will never fail and the loop just keeps running. The syntax is just a bit less obvious to anyone who isnât used to using it.
while :
do
echo Keep running
sleep 3
done
If youâve inserted an infinite loop into a script and want to remind the person who is using it how to exit the script, you can always provide a little guidance as in the example below.
while :
do
echo Keep running
echo "Press CTRL+C to exit"
sleep 3
done
You can do the same thing in a single line by separating the lines shown above with semicolons as shown in the example below.
while true; do echo Keep running; echo 'Press CTRL+C'; sleep 3; done
The command below would work the same. I prefer
while true
because it seems obvious, but any of the examples shown will work as does this one:
while [ 1 ]
do
echo Keep running
echo "Press CTRL+C to exit"
sleep 3
done
Using for
TheÂ
for
 command also provides an easy way to loop forever. While not quite as obvious as the
while true
option, the syntax is reasonably straightforward. You can just replace the parameters in a normal for loop (the start, condition and increment values) that would generally look something like this:
$ for (int i = 0; i < 5; i++)
Instead, use the
for
command with no such values as in the example below.
$ for (( ; ; ))
> do
> echo Keep your spirits up
> echo âPress CTRL+C to exitâ
> sleep 3
> done
Keep your spirits up
âPress CTRL+C to exitâ
Keep your spirits up
âPress CTRL+C to exitâ
Keep your spirits up
âPress CTRL+C to exitâ
And, obviously, press CTRL-C when you want to exit the loop.
Why loop forever?
Of course, youâre not ever going to want to loop forever, but having loops run until you stop them can often be very useful. The script below runs until 5:00 p.m. It uses the
date
command with the
+%H
option to check the time, then reminds you that itâs time to go home and exits. The
sleep 60
command was included to limit the time checking to once a minute. Otherwise, this script could gobble up a lot of CPU time.
#!/bin/bash
while true
do
if [ `date +%H` -ge 17 ]; then
echo Time to go home
exit # exit script
else
sleep 60
fi
done
If you want to exit the loop instead of exiting the script, you can use a
break
command
instead of an exit command as shown in the example below.
#!/bin/bash
while true
do
if [ `date +%H` -ge 17 ]; then
break # exit loop
fi
echo Time to go home
done
Wrap-up
Looping forever is easy. Determining what commands you want to run repeatedly and the conditions under which you want them to stop running are the only challenging parts of putting these forever loops into use.
More Linux tips and how-tos: |
| Markdown | 1. Topics
2. [News](https://www.networkworld.com/news/)
3. [Opinion](https://www.networkworld.com/opinions/)
4. [Features](https://www.networkworld.com/feature/)
5. [Buyerâs Guides](https://www.networkworld.com/enterprise-buyers-guide/)
6. [Newsletters](https://www.networkworld.com/newsletters/signup/)
7. [Resources](https://us.resources.networkworld.com/)
## About
- [About Us](https://www.networkworld.com/about-us/)
- [Advertise](https://foundryco.com/our-brands/networkworld/)
- [Contact Us](https://www.networkworld.com/contact-us/)
- [Editorial Ethics Policy](https://www.networkworld.com/editorial-ethics-policy/)
- [Foundry Careers](https://foundryco.com/work-here/)
- [Reprints](https://www.networkworld.com/contact-us/#republication-permissions)
- [Newsletters](https://www.networkworld.com/newsletters/signup/)
- [Contribute to Network World](https://www.networkworld.com/expert-contributor-network/)
- [Add Network World as a Preferred Source in Google Search](https://www.google.com/preferences/source?q=networkworld.com)
## Policies
- [Terms of Service](https://foundryco.com/terms-of-service-agreement/)
- [Privacy Policy](https://foundryco.com/privacy-policy/)
- [Cookie Policy](https://foundryco.com/cookie-policy/)
- [Copyright Notice](https://foundryco.com/copyright-notice/)
- [Member Preferences](https://www.networkworld.com/member-preferences/)
- [About AdChoices](https://foundryco.com/ad-choices/)
- [Your California Privacy Rights](https://foundryco.com/ccpa/)
## Our Network
- [CIO](https://www.cio.com/)
- [Computerworld](https://www.computerworld.com/)
- [CSO](https://www.csoonline.com/)
- [InfoWorld](https://www.infoworld.com/)
## More
- [News](https://www.networkworld.com/news/)
- [Features](https://www.networkworld.com/feature/)
- [Blogs/Opinion](https://www.networkworld.com/blogs/)
- [BrandPosts](https://www.networkworld.com/brandposts/)
- [Events](https://www.networkworld.com/events/)
- [Videos](https://www.networkworld.com/videos/)
- [Buyerâs Guides](https://www.networkworld.com/enterprise-buyers-guide/)
Close
- [Artificial Intelligence](https://www.networkworld.com/artificial-intelligence/)
- [Generative AI](https://www.networkworld.com/generative-ai/)
- [Careers](https://www.networkworld.com/careers/)
- [Cloud Computing](https://www.networkworld.com/cloud-computing/)
- [CPUs and Processors](https://www.networkworld.com/cpus-and-processors/)
- [Data Center](https://www.networkworld.com/data-center/)
- [Edge Computing](https://www.networkworld.com/edge-computing/)
- [Enterprise Storage](https://www.networkworld.com/enterprise-storage/)
- [Linux](https://www.networkworld.com/linux/)
- [Virtualization](https://www.networkworld.com/virtualization/)
- [Industry](https://www.networkworld.com/industry/)
- [5G](https://www.networkworld.com/5g/)
- [Networking](https://www.networkworld.com/networking/)
- [Internet of Things](https://www.networkworld.com/internet-of-things/)
- [Network Management Software](https://www.networkworld.com/network-management-software/)
- [Network Security](https://www.networkworld.com/network-security/)
- [Security](https://www.networkworld.com/security/)
- [Analytics](https://www.networkworld.com/analytics/)
- [IT Leadership](https://www.networkworld.com/it-leadership/)
- [Enterprise Buyerâs Guides](https://www.networkworld.com/enterprise-buyers-guide/)
Back
Close
## Americas
- United States
Back
Close
Popular Topics
- [Generative AI](https://www.networkworld.com/generative-ai/)
- [Networking](https://www.networkworld.com/networking/)
- [Cloud Computing](https://www.networkworld.com/cloud-computing/)
- [Data Center](https://www.networkworld.com/data-center/)
- [Linux](https://www.networkworld.com/linux/)
- [Virtualization](https://www.networkworld.com/virtualization/)
- Search
- Topics
- [News](https://www.networkworld.com/news/)
- [Opinion](https://www.networkworld.com/opinions/)
- [Features](https://www.networkworld.com/feature/)
- [Buyerâs Guides](https://www.networkworld.com/enterprise-buyers-guide/)
- [Newsletters](https://www.networkworld.com/newsletters/signup/)
- [Resources](https://us.resources.networkworld.com/)
- About
- Policies
- Our Network
- More
Back
## Topics
- [Artificial Intelligence](https://www.networkworld.com/artificial-intelligence/)
- [Generative AI](https://www.networkworld.com/generative-ai/)
- [Careers](https://www.networkworld.com/careers/)
- [Cloud Computing](https://www.networkworld.com/cloud-computing/)
- [CPUs and Processors](https://www.networkworld.com/cpus-and-processors/)
- [Data Center](https://www.networkworld.com/data-center/)
- [Edge Computing](https://www.networkworld.com/edge-computing/)
- [Enterprise Storage](https://www.networkworld.com/enterprise-storage/)
- [Linux](https://www.networkworld.com/linux/)
- [Virtualization](https://www.networkworld.com/virtualization/)
- [Industry](https://www.networkworld.com/industry/)
- [5G](https://www.networkworld.com/5g/)
- [Networking](https://www.networkworld.com/networking/)
- [Internet of Things](https://www.networkworld.com/internet-of-things/)
- [Network Management Software](https://www.networkworld.com/network-management-software/)
- [Network Security](https://www.networkworld.com/network-security/)
- [Security](https://www.networkworld.com/security/)
- [Analytics](https://www.networkworld.com/analytics/)
- [IT Leadership](https://www.networkworld.com/it-leadership/)
- [Enterprise Buyerâs Guides](https://www.networkworld.com/enterprise-buyers-guide/)
Back
## About
- [About Us](https://www.networkworld.com/about-us/)
- [Advertise](https://foundryco.com/our-brands/networkworld/)
- [Contact Us](https://www.networkworld.com/contact-us/)
- [Editorial Ethics Policy](https://www.networkworld.com/editorial-ethics-policy/)
- [Foundry Careers](https://foundryco.com/work-here/)
- [Reprints](https://www.networkworld.com/contact-us/#republication-permissions)
- [Newsletters](https://www.networkworld.com/newsletters/signup/)
- [Contribute to Network World](https://www.networkworld.com/expert-contributor-network/)
- [Add Network World as a Preferred Source in Google Search](https://www.google.com/preferences/source?q=networkworld.com)
Back
## Policies
- [Terms of Service](https://foundryco.com/terms-of-service-agreement/)
- [Privacy Policy](https://foundryco.com/privacy-policy/)
- [Cookie Policy](https://foundryco.com/cookie-policy/)
- [Copyright Notice](https://foundryco.com/copyright-notice/)
- [Member Preferences](https://www.networkworld.com/member-preferences/)
- [About AdChoices](https://foundryco.com/ad-choices/)
- [Your California Privacy Rights](https://foundryco.com/ccpa/)
Back
## Our Network
- [CIO](https://www.cio.com/)
- [Computerworld](https://www.computerworld.com/)
- [CSO](https://www.csoonline.com/)
- [InfoWorld](https://www.infoworld.com/)
Back
## More
- [News](https://www.networkworld.com/news/)
- [Features](https://www.networkworld.com/feature/)
- [Blogs/Opinion](https://www.networkworld.com/blogs/)
- [BrandPosts](https://www.networkworld.com/brandposts/)
- [Events](https://www.networkworld.com/events/)
- [Videos](https://www.networkworld.com/videos/)
- [Buyerâs Guides](https://www.networkworld.com/enterprise-buyers-guide/)
1. [Home](https://www.networkworld.com/)
2. [Blogs](https://www.networkworld.com/blogs/)
3. [Unix as a Second Language](https://www.networkworld.com/blogs/unix-as-a-second-language/)

by [Sandra Henry Stocker](https://www.networkworld.com/profile/sandra-henry-stocker/)
Unix Dweeb
# How to loop forever in bash
How-To
Nov 6, 20245 mins
## Looping forever is easy if you know what commands you want to run repeatedly and the conditions under which you want them to stop running.

Credit: aappp / Shutterstock
There are several ways to loop âforeverâ on Linux commands. In practice, this means only until you decide to stop looping. You might do this while typing commands on the command line, or, more likely, within your scripts. Itâs quite easy. This post provides some examples of how to do this.
The **for** and **while** commands will provide what you need. There are only a few things you have to keep in mind with respect to syntax and techniques.
## Using while
One of the easiest forever-loops involves using the **while** command followed by the condition âtrueâ. You donât have to bother with logic like while \[ 1 -eq 1 \] or similar tests. The **while true** test means the loop will run until you stop it with CTRL-C, close the terminal window, log out, or restart the system. After all, true is always true. Hereâs an example:
```
$ while true
> do
> echo Keep running
> sleep 3
> done
Keep running
Keep running
Keep running
^C
```
The command in the example above will continue running, echo âKeep runningâ after every three-second break. Try âwhile falseâ and it wonât loop even once\!
```
$ while false
> do
> echo Keep running
> sleep 3
> done
$
```
You can do the same thing with a âwhile :â test if you prefer. The key here is that the colon always yields success. Like âwhile trueâ, this test will never fail and the loop just keeps running. The syntax is just a bit less obvious to anyone who isnât used to using it.
```
while :
do
echo Keep running
sleep 3
done
```
If youâve inserted an infinite loop into a script and want to remind the person who is using it how to exit the script, you can always provide a little guidance as in the example below.
```
while :
do
echo Keep running
echo "Press CTRL+C to exit"
sleep 3
done
```
You can do the same thing in a single line by separating the lines shown above with semicolons as shown in the example below.
```
while true; do echo Keep running; echo 'Press CTRL+C'; sleep 3; done
```
The command below would work the same. I prefer **while true** because it seems obvious, but any of the examples shown will work as does this one:
```
while [ 1 ]
do
echo Keep running
echo "Press CTRL+C to exit"
sleep 3
done
```
## **Using for**
The **for** command also provides an easy way to loop forever. While not quite as obvious as the **while true** option, the syntax is reasonably straightforward. You can just replace the parameters in a normal for loop (the start, condition and increment values) that would generally look something like this:
```
$ for (int i = 0; i < 5; i++)
```
Instead, use the **for** command with no such values as in the example below.
```
$ for (( ; ; ))
> do
> echo Keep your spirits up
> echo âPress CTRL+C to exitâ
> sleep 3
> done
Keep your spirits up
âPress CTRL+C to exitâ
Keep your spirits up
âPress CTRL+C to exitâ
Keep your spirits up
âPress CTRL+C to exitâ
```
And, obviously, press CTRL-C when you want to exit the loop.
## Why loop forever?
Of course, youâre not ever going to want to loop forever, but having loops run until you stop them can often be very useful. The script below runs until 5:00 p.m. It uses the **date** command with the **\+%H** option to check the time, then reminds you that itâs time to go home and exits. The **sleep 60** command was included to limit the time checking to once a minute. Otherwise, this script could gobble up a lot of CPU time.
```
#!/bin/bash
while true
do
if [ `date +%H` -ge 17 ]; then
echo Time to go home
exit # exit script
else
sleep 60
fi
done
```
If you want to exit the loop instead of exiting the script, you can use a [**break** command](https://www.networkworld.com/article/971492/using-break-and-continue-to-exit-loops-in-bash.html) instead of an exit command as shown in the example below.
```
#!/bin/bash
while true
do
if [ `date +%H` -ge 17 ]; then
break # exit loop
fi
echo Time to go home
done
```
## Wrap-up
Looping forever is easy. Determining what commands you want to run repeatedly and the conditions under which you want them to stop running are the only challenging parts of putting these forever loops into use.
More Linux tips and how-tos:
- [Cleaning up with apt-get](https://www.networkworld.com/article/968090/cleaning-up-with-apt-get.html)
- [How the Linux screen tool can save your tasks â and your sanity â if SSH is interrupted](https://www.networkworld.com/article/967925/how-the-linux-screen-tool-can-save-your-tasks-and-your-sanity-if-ssh-is-interrupted.html)
- [Using ClamAV to detect viruses on Linux](https://www.networkworld.com/article/970780/using-clamav-to-detect-and-remove-viruses-on-linux.html)
- [Digging up IP addresses with the Linux dig command](https://www.networkworld.com/article/968394/digging-up-ip-addresses-with-the-dig-command.html)
- [Checking Linux system performance with sar](https://www.networkworld.com/article/969982/checking-linux-system-performance-with-sar.html)
[Linux](https://www.networkworld.com/linux/)
## Related content
[Opinion Protecting iOS against the aLTEr attacks By Aaron Woland Jul 10, 2018 5 mins Mobile Security Network Security Small and Medium Business](https://www.networkworld.com/article/966012/protecting-ios-against-the-alter-attacks.html)
[Analysis Rapid7 demystifies penetration testing By Sandra Henry Stocker Feb 8, 2017 3 mins Data Center IT Leadership Network Security](https://www.networkworld.com/article/960143/rapid7-demystifies-penetration-testing.html)
[Reviews Book review â The Book of R: A First Course in Programming and Statistics By Sandra Henry Stocker Oct 11, 2016 4 mins Data Center Open Source Operating Systems](https://www.networkworld.com/article/956194/book-review-the-book-of-r-a-first-course-in-programming-and-statistics.html)
[How-To EZ file extraction on Unix By Sandra Henry Stocker Aug 22, 2016 4 mins Data Center Operating Systems](https://www.networkworld.com/article/954532/ez-file-extraction-on-unix.html)
## Other Sections
- [PODCASTS](https://networkworld.com/podcasts/)
- [VIDEOS](https://networkworld.com/videos/)
- [RESOURCES](https://us.resources.networkworld.com/)
- [EVENTS](https://networkworld.com/events/)
SUBSCRIBE TO OUR NEWSLETTER
### From our editors straight to your inbox
Get started by entering your email address below.

by [Sandra Henry Stocker](https://www.networkworld.com/profile/sandra-henry-stocker/)
Unix Dweeb
1. [Follow Sandra Henry Stocker on X](https://www.twitter.com/bugfarm)
2. [Follow Sandra Henry Stocker on Facebook](https://www.facebook.com/bugfarm)
Sandra Henry-Stocker was a programmer, Linux systems administrator, security engineer and Linux journalist for most of her 30-year career. She describes herself as "USL" (Unix as a second language) but remembers enough English to write books and buy groceries. She lives in the mountains in Virginia where, when not working with or writing about Unix, she's chasing the bears away from her bird feeders. Tune into her [2-Minute Linux](https://www.youtube.com/playlist?list=PLYaGSokOr0MN-fXA0snsiEd1rFcqSGbow) video tutorials and take command of your command line.
## More from this author
- [how-toParameter expansion on Linux Jun 23, 2025 4 mins](https://www.networkworld.com/article/4011151/parameter-expansion-on-linux.html)
- [how-toEssential commands for Linux server management Jun 17, 2025 6 mins](https://www.networkworld.com/article/4008320/essential-commands-for-linux-server-management.html)
- [opinionWhy people love Linux Jun 13, 2025 3 mins](https://www.networkworld.com/article/4006773/why-people-love-linux.html)
- [how-toUnderstanding devices on Linux systems Jun 4, 2025 6 mins](https://www.networkworld.com/article/4001959/understanding-devices-on-linux-systems.html)
- [how-toMany ways to use the date command on Linux May 27, 2025 4 mins](https://www.networkworld.com/article/3996032/many-ways-to-use-the-date-command-on-linux.html)
- [how-toMore math on the Linux command line May 8, 2025 5 mins](https://www.networkworld.com/article/3981326/more-math-on-the-linux-command-line.html)
- [how-toMaking use of your command history on Linux Apr 22, 2025 6 mins](https://www.networkworld.com/article/3542724/making-use-of-command-history-on-linux.html)
- [how-to18 essential commands for new Linux users Apr 22, 2025 10 mins](https://www.networkworld.com/article/3958246/18-essential-commands-for-new-linux-users.html)
## Show me more
Popular
Articles
Podcasts
Videos
[news French government take Bull by horns for âŹ404 million By Maxwell Cooter Apr 3, 20262 mins High-Performance ComputingMergers and AcquisitionsSupercomputers ](https://www.networkworld.com/article/4154186/french-government-take-bull-by-horns-for-e404-million.html)
[news CERT-EU blames Trivy supply chain attack for Europa.eu data breach By John E. Dunn Apr 3, 20264 mins Cloud SecurityCode SecuritySecurity ](https://www.networkworld.com/article/4154185/cert-eu-blames-trivy-supply-chain-attack-for-europa-eu-data-breach-2.html)
[news Cisco: Latest news and insights By Network World staff Apr 3, 202640 mins Network Management SoftwareNetwork SecurityNetworking ](https://www.networkworld.com/article/3523958/cisco-latest-news-and-insights.html)
[podcast Has the hype around âInternet of Thingsâ paid off? \| Ep. 145 Apr 18, 202436 mins IoT PlatformsIoT Security ](https://www.networkworld.com/podcast/2093399/has-the-hype-around-internet-of-things-paid-off-ep-145.html)
[podcast Episode 1: Understanding Ciscoâs Converged SDN Transport Sep 24, 202120 mins Cisco SystemsInternetNetworking ](https://www.networkworld.com/podcast/663051/episode-1-understanding-cisco-s-converged-sdn-transport.html)
[podcast Episode 2: Pluggable Optics and the Internet for the Future Sep 23, 202117 mins Cisco SystemsComputers and PeripheralsInternet ](https://www.networkworld.com/podcast/663053/pluggable-optics-and-the-internet-for-the-future.html)
[video Master Linux Math with the bc Command \| Easy CLI Calculations Explained! Jun 23, 20251 mins Operating Systems ](https://www.networkworld.com/video/4011089/master-linux-math-with-the-bc-command-easy-cli-calculations-explained.html)
[video Master Linux Math in Seconds: How to Use the expr Command Like a Pro Jun 17, 20251 mins Operating Systems ](https://www.networkworld.com/video/4008334/master-linux-math-in-seconds-how-to-use-the-expr-command-like-a-pro.html)
[video How to Do Math in the Command Line Using Double Parentheses Jun 6, 20251 mins Operating Systems ](https://www.networkworld.com/video/4003180/how-to-do-math-in-the-command-line-using-double-parentheses.html)
About
- [About Us](https://www.networkworld.com/about-us/)
- [Advertise](https://foundryco.com/our-brands/networkworld/)
- [Contact Us](https://www.networkworld.com/contact-us/)
- [Editorial Ethics Policy](https://www.networkworld.com/editorial-ethics-policy/)
- [Foundry Careers](https://foundryco.com/work-here/)
- [Reprints](https://www.networkworld.com/contact-us/#republication-permissions)
- [Newsletters](https://www.networkworld.com/newsletters/signup/)
- [BrandPosts](https://www.networkworld.com/brandposts/)
- [News](https://www.networkworld.com/news/)
- [Features](https://www.networkworld.com/feature/)
- [Blogs/Opinion](https://www.networkworld.com/blogs/)
- [Add Network World as a Preferred Source in Google Search](https://www.google.com/preferences/source?q=networkworld.com)
Policies
- [Terms of Service](https://foundryco.com/terms-of-service-agreement/)
- [Privacy Policy](https://foundryco.com/privacy-policy/)
- [Cookie Policy](https://foundryco.com/cookie-policy/)
- [Copyright Notice](https://foundryco.com/copyright-notice/)
- [Member Preferences](https://www.networkworld.com/member-preferences/)
- [About AdChoices](https://foundryco.com/ad-choices/)
- [Your California Privacy Rights](https://foundryco.com/ccpa/)
- [Privacy Settings]()
Our Network
- [CIO](https://www.cio.com/)
- [Computerworld](https://www.computerworld.com/)
- [CSO Online](https://www.csoonline.com/)
- [InfoWorld](https://www.infoworld.com/)
- [Facebook](https://www.facebook.com/NetworkWorld)
- [X](https://twitter.com/networkworld)
- [YouTube](https://www.youtube.com/idgtechtalk)
- [Google News](https://news.google.com/publications/CAAqLAgKIiZDQklTRmdnTWFoSUtFRzVsZEhkdmNtdDNiM0pzWkM1amIyMG9BQVAB)
- [LinkedIn](https://www.linkedin.com/company/network-world)
[Š 2026 FoundryCo, Inc. All Rights Reserved.](https://foundryco.com/terms-of-service-agreement/) |
| Readable Markdown | There are several ways to loop âforeverâ on Linux commands. In practice, this means only until you decide to stop looping. You might do this while typing commands on the command line, or, more likely, within your scripts. Itâs quite easy. This post provides some examples of how to do this.
The **for** and **while** commands will provide what you need. There are only a few things you have to keep in mind with respect to syntax and techniques.
## Using while
One of the easiest forever-loops involves using the **while** command followed by the condition âtrueâ. You donât have to bother with logic like while \[ 1 -eq 1 \] or similar tests. The **while true** test means the loop will run until you stop it with CTRL-C, close the terminal window, log out, or restart the system. After all, true is always true. Hereâs an example:
```
$ while true
> do
> echo Keep running
> sleep 3
> done
Keep running
Keep running
Keep running
^C
```
The command in the example above will continue running, echo âKeep runningâ after every three-second break. Try âwhile falseâ and it wonât loop even once\!
```
$ while false
> do
> echo Keep running
> sleep 3
> done
$
```
You can do the same thing with a âwhile :â test if you prefer. The key here is that the colon always yields success. Like âwhile trueâ, this test will never fail and the loop just keeps running. The syntax is just a bit less obvious to anyone who isnât used to using it.
```
while :
do
echo Keep running
sleep 3
done
```
If youâve inserted an infinite loop into a script and want to remind the person who is using it how to exit the script, you can always provide a little guidance as in the example below.
```
while :
do
echo Keep running
echo "Press CTRL+C to exit"
sleep 3
done
```
You can do the same thing in a single line by separating the lines shown above with semicolons as shown in the example below.
```
while true; do echo Keep running; echo 'Press CTRL+C'; sleep 3; done
```
The command below would work the same. I prefer **while true** because it seems obvious, but any of the examples shown will work as does this one:
```
while [ 1 ]
do
echo Keep running
echo "Press CTRL+C to exit"
sleep 3
done
```
## **Using for**
The **for** command also provides an easy way to loop forever. While not quite as obvious as the **while true** option, the syntax is reasonably straightforward. You can just replace the parameters in a normal for loop (the start, condition and increment values) that would generally look something like this:
```
$ for (int i = 0; i < 5; i++)
```
Instead, use the **for** command with no such values as in the example below.
```
$ for (( ; ; ))
> do
> echo Keep your spirits up
> echo âPress CTRL+C to exitâ
> sleep 3
> done
Keep your spirits up
âPress CTRL+C to exitâ
Keep your spirits up
âPress CTRL+C to exitâ
Keep your spirits up
âPress CTRL+C to exitâ
```
And, obviously, press CTRL-C when you want to exit the loop.
## Why loop forever?
Of course, youâre not ever going to want to loop forever, but having loops run until you stop them can often be very useful. The script below runs until 5:00 p.m. It uses the **date** command with the **\+%H** option to check the time, then reminds you that itâs time to go home and exits. The **sleep 60** command was included to limit the time checking to once a minute. Otherwise, this script could gobble up a lot of CPU time.
```
#!/bin/bashwhile true
do
if [ `date +%H` -ge 17 ]; then
echo Time to go home
exit # exit script
else
sleep 60
fi
done
```
If you want to exit the loop instead of exiting the script, you can use a [**break** command](https://www.networkworld.com/article/971492/using-break-and-continue-to-exit-loops-in-bash.html) instead of an exit command as shown in the example below.
```
#!/bin/bashwhile true
do
if [ `date +%H` -ge 17 ]; then
break # exit loop
fi
echo Time to go home
done
```
## Wrap-up
Looping forever is easy. Determining what commands you want to run repeatedly and the conditions under which you want them to stop running are the only challenging parts of putting these forever loops into use.
More Linux tips and how-tos: |
| Shard | 111 (laksa) |
| Root Hash | 6029952698187917311 |
| Unparsed URL | com,networkworld!www,/article/3600146/how-to-loop-forever-in-bash.html s443 |