0
0
Bash Scriptingscripting~5 mins

Infinite loops in Bash Scripting

Choose your learning style9 modes available
Introduction
Infinite loops keep running a set of commands forever until you stop them. They help when you want a task to repeat without stopping.
Keep checking if a file exists and act when it appears.
Run a server that listens for requests all the time.
Keep monitoring system resources continuously.
Create a simple menu that shows until the user chooses to exit.
Syntax
Bash Scripting
while true; do
  # commands
  sleep 1
 done
The keyword true always returns success, so the loop never ends on its own.
Use sleep to pause between commands and avoid using too much CPU.
Examples
Prints "Hello" every second forever.
Bash Scripting
while true; do
  echo "Hello"
  sleep 1
 done
Prints the current date every 2 seconds. The colon : is a shortcut for true.
Bash Scripting
while :; do
  date
  sleep 2
 done
Another way to write an infinite loop using a for loop syntax.
Bash Scripting
for (( ; ; )); do
  echo "Looping"
  sleep 3
 done
Sample Program
This script counts from 1 to 5, printing each number every second. It stops the infinite loop using break when count is greater than 5.
Bash Scripting
#!/bin/bash

count=1
while true; do
  echo "Count is $count"
  ((count++))
  if [ $count -gt 5 ]; then
    echo "Stopping loop"
    break
  fi
  sleep 1
 done
OutputSuccess
Important Notes
Always have a way to stop infinite loops, like a break condition or pressing Ctrl+C.
Without pauses like sleep, infinite loops can use a lot of CPU and slow down your system.
Infinite loops are useful but can cause problems if not controlled carefully.
Summary
Infinite loops repeat commands forever until stopped.
Use while true, while :, or for (( ; ; )) to create them.
Always include a way to exit or pause to keep your system safe.