Intentional infinite loops

It’s happened to all of us. A script just locks up and we’re unsure why. At
closer inspection we find that we’re written a loop that has no terminating
condition. It is an endless loop and in many cases consumes memory until it
crashes.

But what if you want to do this intentionally? Happened to me the other day. I
have a command that I run multiple times a day. I grew tired of pressing up and
then hitting enter (assuming the correct command popped up next). I set out to
write a shell script to run endlessly and run the command in question when I
pressed enter.

Another use case would be when you are writing a daemon. It needs to run in the
background, possibly sleep for a period of time before running again.

The concept of an infinite loop is pretty simple. You need a loop that has a
condition that always validates as true. Here is an example of what I did. Keep
in mind that you can consolidate this down to a single line or swap out the read
command for a sleep command if you want it to run unattended.

while :
do
  read -p "Press <enter> to do continue..."
  echo "This is where you put your commands!!"
done
Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.