Infinite while loop

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← While loopHomeUntil loop →

You can use : special command with while loop to tests or set an infinite loop or an endless loop. An infinite loop occurs when the condition will never be met, due to some inherent characteristic of the loop. There are a few situations when this is desired behavior. For example, the menu driven program typically continue till user selects to exit his or her main menu (loop). To set an infinite while loop use:

  1. true command - do nothing, successfully (always returns exit code 0)
  2. false command - do nothing, unsuccessfully (always returns exit code 1)
  3. : command - no effect; the command does nothing (always returns exit code 0)

Syntax

Use : command to set an infinite loop:

#!/bin/bash
# Recommend syntax for setting an infinite while loop
while :
do
	echo "Do something; hit [CTRL+C] to stop!"
done

Use the true command to set an infinite loop:

#!/bin/bash
while true
do
	echo "Do something; hit [CTRL+C] to stop!"
done

Use the false command to set an infinite loop:

#!/bin/bash
while false
do
	echo "Do something; hit [CTRL+C] to stop!"
done

Note the first syntax is recommended as : is part of shell itself i.e. : is a shell builtin command.

A menu driven program using while loop

The following menu driven program typically continues till user selects to exit by pressing 4 option. The case statement is used to match values against $choice variable and it will take appropriate action according to users choice. Create a shell script called menu.sh:

#!/bin/bash
# set an infinite loop
while :
do
	clear
        # display menu
        echo "Server Name - $(hostname)"
	echo "-------------------------------"
	echo "     M A I N - M E N U"
	echo "-------------------------------"
	echo "1. Display date and time."
	echo "2. Display what users are doing."
	echo "3. Display network connections."
	echo "4. Exit"
        # get input from the user 
	read -p "Enter your choice [ 1 -4 ] " choice
        # make decision using case..in..esac 
	case $choice in
		1)
			echo "Today is $(date)"
			read -p "Press [Enter] key to continue..." readEnterKey
			;;
		2) 
			w	
			read -p "Press [Enter] key to continue..." readEnterKey
			;;
		3)
			netstat -nat
			read -p "Press [Enter] key to continue..." readEnterKey
			;;
		4)
			echo "Bye!"
			exit 0
			;;
		*)
			echo "Error: Invalid option..."	
			read -p "Press [Enter] key to continue..." readEnterKey
			;;
	esac		
 
done

Save and close the file. Run it as follows:

chmod +x menu.sh
./menu.sh

Sample outputs:

menu.sh program output
← While loopHomeUntil loop →