- Buy Microsoft Visio Professional or Microsoft Project Professional 2024 for just $80
- Get Microsoft Office Pro and Windows 11 Pro for 87% off with this bundle
- Buy or gift a Babbel subscription for 78% off to learn a new language - new low price
- Join BJ's Wholesale Club for just $20 right now to save on holiday shopping
- This $28 'magic arm' makes taking pictures so much easier (and it's only $20 for Black Friday)
How to loop forever in bash
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.