Skip to content

How to Create Infinite while Loop in Bash Script

Advertisement

Command:



while true;do echo “Press CTRL+C to Exit”; done


Example 1:

Some times we are required to execute some commands or processes continuously until stop it forcefully or conditionally. The following example of while loop will run continuously until stopped forcefully using ctrl + c.


while true
do
  echo "Press CTRL+C to Exit"
done

Example 2:

We can also use colon “:” in place of “true” with while loop for creating infinite loop in bash script.


while :
do
  echo "Press CTRL+C to Exit"
done

Stopping Loop on Condition:

In case we need to terminate an infinite while loop on matching certain condition’s, we can use break keyword to exit from running loop.

while :
do
  echo "Press CTRL+C to Exit"
  if [ condition ]
  then
      break
  fi
done

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top