How to Create Infinite Loop in Bash [7 Cases]

To create an infinite loop in Bash, select the while loop and keep the loop condition true. It is a structure that repeats a set of commands indefinitely. It tirelessly continues as long as the loop remains uninterrupted. This is an excellent approach to automating complex tasks and doing certain operations repetitively before a specific scenario occurs. In this article, I will explore the infinite loop in Bash.

7 Cases of Infinite Loop in Bash

An infinite loop can be achieved using a for loop, a while loop, or an until loop. Here, I will show you how to create an infinite loop, control an infinite loop, exit an infinite loop, create a nested infinite loop, and handle signals.

1. Creating Infinite “for” Loop in Bash

A for loop does not have any initialization, loop condition, or iteration expression. An infinite for loop will execute the code block inside it repeatedly unless CTRL+C is pressed or the break command terminates the loop. Here is a bash script to create an infinite for loop:

#!/bin/bash
for (( ; ; ))
do
    echo "Press CTRL+C to stop the loop."
    sleep 1
done
EXPLANATION

The for (( ; ; )) starts an infinite for loop without initialization, condition, or iteration expression. Then the echo command prints a message on the terminal repeatedly.

The infinite for loop printed a message repeatedly.

2. Exit Infinite Loop in Bash Using “case” Statement

The infinite loop continues execution until the break command is encountered within the loop. The programmers can set a conditional break statement incorporating it in the case statement to terminate the bash script on a specific loop condition. Here is a Bash script to exit infinite for loop in bash using a case statement:

#!/bin/bash
for (( ; ; ))
do
    echo "Enter yes, no, or quit: "
    read r
    case $r in
        yes) echo "Given: yes";;
        no) echo "Given: no";;
        quit) 
            echo "Terminating the loop."
            break ;;
        *)
        echo "Invalid input. Please enter yes, no, or quit." ;;
    esac
done
EXPLANATION

The read command reads input from the user as variable r. Then the case statement looks to match the r with yes, no, and quit and prints a message according to the match result.

The case statement terminate the infinite loop with break command.

3. Nested Infinite Loops in Bash

In a nested loop combination, the inner, outer, or both loops can be infinite. This type of nested infinite loop is necessary to iterate over complex patterns, multidimensional data, and simulating grids or matrics. Here is a bash script having a nested infinite loop:

#!/bin/bash
count_out=1
for (( ; ; ))
do
    count_in=1
    while [ $count_in -le 5 ]
    do
        echo "$count_out.$count_in"
        sleep 1
        ((count_in++))
    done
    ((count_out++))
done
EXPLANATION

Here, for (( ; ; )) initiates an infinite outer for loop. Then, while [ $count_in -le 5 ] initiates the inner loop that iterates as long as the count_1 value is less than or equal to 5 and prints a combination of the values of a count_in and count_out variable on each iteration.

Nested infinite loop printed a series of numbers.

4. Controlling Infinite Loops with ‘break’ Statement

The loop condition for an infinite loop is, by default, true. Using a break statement inside an if statement is an efficient approach for terminating the loop. Here is a bash script where the break statement controls an infinite loop:

#!/bin/bash
a=10
for (( ; ; ))
do
    echo $a
    ((a--))
    if [ $a -lt 5 ]; then
        break;
    fi
done
echo "Value of a is out of condition."
EXPLANATION

The for (( ; ; )) initiates an infinite loop, then the echo command prints the value of a, and then ((a--)) decreases the value of a by one. After that, the if [ $a -lt 5 ] checks whether a is less than 5. If so, then the break command terminates the loop.

The break statement stopped the infinite loop.

5. Handling Signals in Infinite Loops

The trap command executes a predefined command according to the signal it receives. It is a tool to print a specific message on the terminal when an infinite loop gets interrupted. Here is a bash script which will do such:

#!/bin/bash
trap 'echo "The Infinite Loop interrupted"; exit' INT
for (( ; ; ))
do
    echo "The Infinite Loop Executing…"
    sleep 1
done
EXPLANATION

The trap 'echo "The Infinite Loop interrupted"; exit' INT command sets up a signal trap which specifies to print a message when an interrupt signal is generated by pressing CTRL+C and exits the script. After that, for (( ; ; )) initiates an infinite while loop.

The trap command printed a message according to singal.

6. Infinite “until” Loop in Bash

The until loop executes a set of commands inside it as long as the loop condition remains false. Setting the until loop condition constant to false makes an infinite until loop. Being an infinite until loop, it can execute repeatedly unless loop conditions become true or the break statement terminates the loop. Here is a Bash script containing an infinite until loop:

#!/bin/bash
until false
do
    echo "This is an infinite loop. Press [Ctrl+C] to exit."
    sleep 1
done
EXPLANATION

The until false initiates an infinite until loop as the condition of the until loop is false. Nothing from the loop iteration will make the condition false and terminate the infinite loop.

The while loop executes infinitely.

7. Infinite “while” Loop in Bash

Keeping the condition of a while loop makes it an infinite loop. The while loop will iterate as long as the condition is true. This is the most straightforward infinite loop. Here is a Bash script which will execute a while loop infinitely:

#!/bin/bash
while true
do
    echo "Press [CTRL+C] to stop the Loop."
    sleep 1
done
EXPLANATION

The while loop conditions are true, which marks an infinite loop. Then, the echo command printed a message on the terminal, and the sleep command paused the execution for 1 second.

The CTRL+C stopped the execution of infinite while loop.

Troubleshooting Common Infinite Loop Issues

Infinite loop faces some issues during operation. Some of these issues are listed here:

Loop Running Indefinitely Issue

If the condition remains true during eternal iteration, nothing makes the condition false. Therefore, this loop will run indefinitely. Here is a Bash script having such an issue:

#!/bin/bash
a=10
for (( ; ; ))
do
    echo "Counter: $a"
    ((a++))
    sleep 1
done

Infinite Loop Not Running Issue

Infinite loop not running at all is another issue faced by Bash programmers. It happens if the condition of a loop is set as false. In such a situation, the loop will not be executed as nothing is here to alter the condition to true. The bash script below has the same issue:

#!/bin/bash
for (( ; false;))
do
    echo 'The loop will never be executed.'
    sleep 1
done
Note: To overcome these types of issues, never miss to set an appropriate loop condition while defining a loop.

Best Practices and Optimization Tips

Some practice, caution, and optimization tips can make the Bash scripting experience efficient and flawless. Here are some tips on this:

  1. Cross Check: Before executing an infinite loop, check the loop execution with a limited number of iterations. If any issues occur, it can be solved easily.
  2. Stop Switch: Place a break statement properly or press CTRL+C to interrupt an infinite loop when needed.
  3. Resource Usage: Operation inside the infinite loop might consume system resources. To limit the system usage in total execution, put the sleep statement to delay some seconds before the next iteration.

Conclusion

In conclusion, the application of infinite loops in Bash is a powerful tool in scripting for various scenarios. This article will help the advanced and beginners learn and implement the infinite loop in Bash, ensuring the smooth and controlled execution of commands.

People Also Ask

How do you make an infinite loop in Bash?

To make an infinite loop in Bash, use a for or while loop with true as a constant loop condition. Thus, the loop runs infinitely until it is explicitly interrupted.

How do you break an infinite loop?

To break an infinite loop, press CTRL+C on the keyboard. It will send a signal to interrupt the execution of the loop, which is running indefinitely.

What is the infinite loop format?

An infinite loop is a loop that executes a set of commands repeatedly indefinitely. It does not depend on any condition to control the execution, determining where to end.

How do I exit a Bash loop?

You can exit a Bash loop by using the break statement. This is a loop control statement that terminates a loop and moves to execute the subsequent commands after the loop.

What type of error is an infinite loop?

The infinite loop is a logical error. Usually, programs are finite sets of commands that execute in a limited time.

What is the difference between finite and infinite loop?

The finite loop is a loop that executes a set of commands repeatedly for a specified number of times. However, an infinite loop executes the same commands repeatedly for countless times.

Related Articles


<< Go Back to For Loop in BashLoops in Bash | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment