- The 10 best tech stocking stuffers people will actually want
- Prime Video now offers AI-generated show recaps - but no spoilers!
- What Amazon says about Kindle Colorsoft's screen discoloration issues
- The best MagSafe battery packs of 2024: Expert tested and reviewed
- Microsoft joins multi-AI agent fray with Magnetic-One
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.