Infinite loops

An infinite loop can be written using the true builtin with a while statement:

while true ; do
    printf 'Infinite loop!\n'
    sleep 1
done

The preceding code will print the "Infinite loop!" string followed be a newline endlessly, waiting for a second after each print. You can press Ctrl + C to stop the loop. The loop will never terminate on its own, because the true builtin in Bash always exits with status 0 (success), by design.

You will sometimes see the colon builtin, :, used instead of true; the effect is the same. You may find true is easier to read.

An infinite loop may not seem very useful at first, especially given Bash is not an event-driven or functional language that might require an event loop. There are still situations ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.