Create A Infinite Loop in Shell Script
Abstract: 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 t
Question – How do I create an infinite loop in shell script on Unix/Linux operating system?
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 LoopIn this scenario, which loop is the best option. The following syntax is used for create infinite while loop in a shell script.
Loop Example:
#!/usr/bin/env bash while : do echo "Press [CTRL+C] to exit this loop..." # Add more instructions here sleep 2 done12345678#!/usr/bin/env bash while :do echo "Press [CTRL+C] to exit this loop..." # Add more instructions here sleep 2doneYou 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:
#!/usr/bin/env bash while true do echo "Press [CTRL+C] to exit this loop..." # Add more instructions here sleep 2 done12345678#!/usr/bin/env bash while truedo echo "Press [CTRL+C] to exit this loop..." # Add more instructions here sleep 2done Add Exist Instruction in Infinite LoopSometimes 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.
#!/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 done12345678910111213#!/usr/bin/env bash while truedo echo "Press [CTRL+C] to exit this loop..." # Add more instructions here sleep 2 if [ condition ] then break fidoneAdd a if statement in above loop to break on matching condition.