Bash While True

Bash While True is a bash While Loop where the condition is always true and the loop executes infinitely.

This kind of infinite loop is used to continuously execute a task, or continuously wait for an events to happen, etc.

In this tutorial, we will learn how to write a While True loop, with example bash scripts.

Sytnax

The syntax of While loop with condition always true is

while true
do
    statement(s)
done
ADVERTISEMENT

Examples

While True

In the following script, we print integers from 0 indefinitely using While True loop.

Example.sh

i=0

while true
do
   echo "$i"
   let i++
done

Output

0
1
2
3
...

While True with Sleep

If we are using While True statement to run the loop indefinitely, and if we would like insert a small pause between loop executions to avoid a CPU load, use sleep command with required amount of time to sleep between iterations.

Example.sh

i=0

while true
do
   echo "$i"
   let i++
   sleep 1
done

Output

0
1
2
3
...

Now, there is at least one second gap between iterations, since we have given sleep 1 command.

Conclusion

In this Bash Tutorial, we have learnt how to run while loop indefinitely using While loop statement with condition as true.