Bash Infinite Loop Examples

www.laut‮‬turi.com
Bash Infinite Loop Examples

An infinite loop is a loop that continues to run indefinitely, without ever reaching a termination condition. In Bash, you can create an infinite loop using the while true construct. Here are some examples of how to use the while true loop in Bash:

  1. Basic infinite loop:
while true; do
  echo "This is an infinite loop"
done

In this example, the while true loop will run indefinitely, printing the string "This is an infinite loop" on each iteration. The while true loop will never reach a termination condition, so it will continue to run until it is interrupted by the user or by another event.

  1. Infinite loop with a break condition:
while true; do
  read -p "Enter 'q' to quit: " input
  if [ "$input" = "q" ]; then
    break
  fi
done

In this example, the while true loop will run indefinitely, prompting the user to enter the letter "q" on each iteration. If the user enters "q", the break keyword is used to break out of the loop and terminate it. Otherwise, the loop will continue to run indefinitely.

  1. Infinite loop with a sleep interval:
while true; do
  date
  sleep 1
done

In this example, the while true loop will run indefinitely, printing the current date and time on each iteration. The sleep 1 command is used to pause the loop for one second on each iteration, so the date and time will be printed at regular intervals.

These are just a few examples of how to use the while true loop in Bash to create an infinite loop. You can use this loop in many different ways to perform repetitive tasks in your Bash scripts. Consult the Bash documentation for more information about using the while loop and the break and sleep commands in Bash.

Created Time:2017-10-16 14:38:38  Author:lautturi