Bash Infinite Loop Examples

How do I write an infinite loop in Bash script under Linux or UNIX like operating systems?

An infinite loop is nothing but a sequence of instructions which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over. The syntax is as follows using the while loop:

ADVERTISEMENTS

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

This is a loop that will forever print “Press [CTRL+C] to stop..”. Please note that : is the null command. The null command does nothing and its exit status is always set to true. You can modify the above as follows to improve the readability:

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

A single-line bash infinite while loop syntax is as follows:

 while :; do echo 'Hit CTRL+C'; sleep 1; done

OR

 while true; do echo 'Hit CTRL+C'; sleep 1; done

Bash for infinite loop example

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

How Do I Escape the Loop?

A for or while loop may be escaped with a break statement when certain condition is satisfied:

 ### for loop example ###
for (( ; ; ))
do
   echo "Pres CTRL+C to stop..."
   sleep 1
   if (disaster-condition)
   then
	break       	   #Abandon the loop.
   fi
done

OR

 ### while loop example ###
while :
do
   echo "Pres CTRL+C to stop..."
   sleep 1
   if (disaster-condition)
   then
	break       	   #Abandon the loop.
   fi
done

You can also use the case statement to esacpe with a break statement:

while :
do 
     ### add some input and output here ###
     case $var in
       yes) do something ;;
       no) do something ;;
       quit) break ;;        ##Abandon the loop.
     ease
done

Example

A sample shell script to demonstrate the actual usage of an infinite loop and the break statement:

#!/bin/bash
# Purpose: Display various options to operator using menus
# Author: Vivek Gite < vivek @ nixcraft . com > under GPL v2.0+
# ---------------------------------------------------------------------------
# capture CTRL+C, CTRL+Z and quit singles using the trap
trap '' SIGINT
trap ''  SIGQUIT
trap '' SIGTSTP
 
# display message and pause 
pause(){
	local m="$@"
	echo "$m"
	read -p "Press [Enter] key to continue..." key
}
 
# set an 
while :
do
	# show menu
	clear
	echo "---------------------------------"
	echo "	     M A I N - M E N U"
	echo "---------------------------------"
	echo "1. Show current date/time"
	echo "2. Show what users are doing"
	echo "3. Show top memory & cpu eating process"
	echo "4. Show network stats"
	echo "5. Exit"
	echo "---------------------------------"
	read -r -p "Enter your choice [1-5] : " c
	# take action
	case $c in
		1) pause "$(date)";;
		2) w| less;;
		3) echo '*** Top 10 Memory eating process:'; ps -auxf | sort -nr -k 4 | head -10; 
		   echo; echo '*** Top 10 CPU eating process:';ps -auxf | sort -nr -k 3 | head -10; 
		   echo;  pause;;
		4) netstat -s | less;;
		5) break;;
		*) Pause "Select between 1 to 5 only"
	esac
done

See also:

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
15 comments… add one
  • Alexander Lagerström Mar 10, 2011 @ 17:37

    somevar=1 && while [ $somevar -lt 2 ]; do echo “Something”;done

  • Eric Smith Jul 19, 2011 @ 14:13

    Great article mate! Used this one yesterday :-)

  • ilkata89 Oct 7, 2012 @ 19:40

    An example in a book that I am reading is as follows:

    #!/bin/sh
    
    yes_or_no()
    {
      echo "Is your name $* ?"
      while true
      do
        echo -n "Enter yes or no: "
        read x
        case "$x" in
          y | yes ) return 0;;
          n | no  ) return 1;;
          *       ) echo "Answers can only be yes or no";;
          esac
      done
    }
    
    echo "Original parameters are $*"
    
    if yes_or_no "$1"
    then
      echo "Hi $1, nice name."
    else
      echo "Never mind."
    fi
    
    exit 0
    

    I don’t understand what makes the infinate while loop get terminated in the yes_or_no() function.

    Thanks

    • Carl May 1, 2013 @ 12:54

      In ilkata89’s code, the return statements cause the yes_or_no() function to end, thus terminating the loop.

  • rickard Aug 2, 2013 @ 7:13

    The while loop is in a function, note the ().

    The if else statement calls the function and if your name is the same as $0 then the condition is true and if not it returns 0 and prints out Never mind and exits.

  • Robert Nov 25, 2013 @ 15:47

    Great example but do you have similar one to make program use up available memory?
    Need to do some testing but need a memory hog program.

  • NT4Boy Dec 2, 2013 @ 14:36

    while true; do cat big.random.block; | dd of=/dev/st0 bs=1024

    this is a bit of a script for overwriting random data via a file created that’s 10meg in size to tapes, But, it doesn’t stop when the tape is full,….
    So, how should this “true” become untrue so it exits please?

  • andy Jun 8, 2014 @ 6:11

    Just what I needed! Thanks so much.

    I’m using the following line:

    $ for (( ;; )) do ping -c 1 google.com; sleep 15; done

    This is for checking whether my internet connection has “recovered” after suspend/hibernate. It will always take quite awhile here, and I was tired of repeatedly hacking in “ping…” until there was some response…

    • Alexey Serikov Nov 12, 2014 @ 10:59

      [code]
      ping -i 15 google.co
      [/code]
      will have the same effect

  • Townville Apr 26, 2015 @ 21:29

    Nice… use it for my server

  • Jefferson Oct 29, 2015 @ 22:55

    thanks :) me ajudou muito

  • Alessandro Nov 19, 2015 @ 23:50

    I always use this:

    while [ true ] ; do something() ; done

  • Cpt. Varel May 16, 2017 @ 8:35

    The case “*)” in the “Example” above is not working:
    *) Pause “Select between 1 to 5 only”

    The message is not displayed if a number >5 is entered.

    I’ve changed it to

    *) echo “Select between 1 to 5 only”; pause

    Then it’s working. Only for the sake of form :)

    • Cpt. Varel May 16, 2017 @ 8:50

      Forget my 1st comment.
      Just saw that “Pause” was written up.
      If it is small-written, it works naturally ;)

  • d.r. Aug 10, 2020 @ 12:23

    This joke can break your filesystem:

    #!/bin/bash
    while :
    do
    	mkdir a
    	cd a
    done
    

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.