Infinite Loop

To write an infinite loop in Bash script, we can use any of the looping statements like For loop, While loop and Until loop.

In this tutorial, we will learn how to write an infinite loop, with example bash scripts.

Infinite While Loop

If the condition in While loop statement is always true, then this While loop becomes an infinite loop.

The syntax of infinite While loop is

</>
Copy
while true
do
    statement(s)
done

or

</>
Copy
while :
do
    statement(s)
done

In the following script, we print the string “hello world” indefinitely using While True loop.

Example.sh

</>
Copy
while true
do
   echo "hello world"
   sleep 1
done

Output

hello world
hello world
hello world
...

Infinite For Loop

If no condition is specified in For loop statement, then the for loop can run indefinitely.

The syntax of infinite For loop is

</>
Copy
for (( ; ; ))
do
    statement(s)
done

In the following script, we print a string “hello world” indefinitely using infinite For loop.

Example.sh

</>
Copy
for (( ; ; ))
do
   echo "hello world"
   sleep 1
done

Output

hello world
hello world
hello world
...

Infinite Until Loop

If the condition in Until loop statement is always false, then this Until loop becomes an infinite loop.

The syntax of infinite while loop is

</>
Copy
until false
do
    statement(s)
done

In the following script, we write an infinite Until loop.

Example.sh

</>
Copy
until false
do
   echo "hello world"
   sleep 1
done

Output

hello world
hello world
hello world
...

Conclusion

In this Bash Tutorial, we have learnt how to write infinite loops in Bash script using For loop, While loop and Until loop.