Bash infinite loop

#!/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

Tags: cli, linux, snipped