Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Programming»Bash Shell»Create A Infinite Loop in Shell Script

    Create A Infinite Loop in Shell Script

    By RahulAugust 20, 20201 Min Read

    Question – How do I create an infinite loop in shell script on Unix/Linux operating system?

    Advertisement

    An infinite loop is used for running a set of instruction with never ending repeat. In this we create a loop which runs endlessly and keep executing the instructions until force stopped externally.

    Bash Infinite While Loop

    In this scenario, which loop is the best option. The following syntax is used for create infinite while loop in a shell script.

    Loop Example:

    1
    2
    3
    4
    5
    6
    7
    8
    #!/usr/bin/env bash
     
    while :
    do
        echo "Press [CTRL+C] to exit this loop..."
        # Add more instructions here
        sleep 2
    done

    You can also Unix true command with while loop to run it endlessly. The while loop syntax with true command will look like below example.

    Loop Example:

    1
    2
    3
    4
    5
    6
    7
    8
    #!/usr/bin/env bash
     
    while true
    do
        echo "Press [CTRL+C] to exit this loop..."
        # Add more instructions here
        sleep 2
    done

    Add Exist Instruction in Infinite Loop

    Sometimes you may need to exit from a never ending loop based on a condition. If a specific condition meet and your want that infinite loop should break on that condition.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #!/usr/bin/env bash
     
    while true
    do
        echo "Press [CTRL+C] to exit this loop..."
        # Add more instructions here
        sleep 2
     
       if [ condition ]
       then
           break
       fi
    done

    Add a if statement in above loop to break on matching condition.

    bash loop while
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    10 Bash Tricks Every Developer Should Know

    Understanding 2>&1 in Bash: A Beginner’s Guide

    Best Practices and Tips for Writing Shell Scripts as Pro

    Add A Comment

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • How to List Manually Installed Packages in Ubuntu & Debian
    • 10 Bash Tricks Every Developer Should Know
    • How to Validate Email Address in JavaScript
    • Firewalld: Common Firewall Rules and Commands
    • 12 Apk Commands in Alpine Linux Package Management
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.