Linux / UNIX: Bash Loop Forever

Linux / UNIX: Bash Loop Forever

To create a loop that runs forever in Bash, you can use the while loop with the true command. The true command is a built-in command that always returns a success exit code (0), and the while loop will continue to run as long as the command returns a success exit code.

For example, to create a loop that runs forever, you can use the following syntax:

‮ refer‬to:lautturi.com
while true; do
  # commands to run in the loop go here
done

This will create a while loop that runs the specified commands indefinitely. The true command will always return a success exit code, so the loop will never end unless it is interrupted by a signal or an error occurs in one of the commands.

It is important to note that while this type of loop can be useful in some situations, it can also cause problems if not used carefully. For example, if the commands in the loop are not designed to terminate, the loop will continue to run indefinitely, potentially consuming system resources and causing performance issues.

Therefore, it is recommended to use this type of loop only when necessary and to include checks or conditions in the loop to ensure that it will terminate in a timely manner. For example, you can include a counter or timer in the loop to limit the number of iterations or the amount of time that the loop runs.

counter=0
while true; do
  # commands to run in the loop go here
  
  # increment the counter
  ((counter++))
  
  # terminate the loop if the counter reaches 10
  if [[ $counter -eq 10 ]]; then
    break
  fi
done

In this example, the while loop will run the specified commands 10 times before terminating. This can help prevent the loop from running indefinitely and consuming system resources.

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