0
0
Bash Scriptingscripting~5 mins

while loop in Bash Scripting

Choose your learning style9 modes available
Introduction
A while loop lets you repeat a set of commands as long as a condition is true. It helps automate tasks that need to happen multiple times.
When you want to keep asking a user for input until they give a valid answer.
When you want to process lines in a file one by one until the end.
When you want to repeat a task until a certain condition changes, like waiting for a file to appear.
When you want to count or do something a specific number of times using a condition.
When you want to keep checking system status until it meets your needs.
Syntax
Bash Scripting
while [ condition ]
do
  commands
 done
The condition is checked before each loop. If true, commands run; if false, loop stops.
Use square brackets [ ] with spaces around the condition for test expressions.
Examples
This loop prints the count from 1 to 3, increasing count each time.
Bash Scripting
count=1
while [ $count -le 3 ]
do
  echo "Count is $count"
  count=$((count + 1))
done
This loop runs forever until you stop it manually.
Bash Scripting
while true
 do
  echo "Press Ctrl+C to stop"
  sleep 1
done
This loop asks the user to type 'yes' and repeats until they do.
Bash Scripting
input=""
while [ "$input" != "yes" ]
do
  read -p "Type yes to continue: " input
done
Sample Program
This script prints 'Loop number' followed by numbers 1 to 5 using a while loop.
Bash Scripting
#!/bin/bash

count=1
while [ $count -le 5 ]
do
  echo "Loop number $count"
  count=$((count + 1))
done
OutputSuccess
Important Notes
Always make sure the condition will eventually become false, or the loop will run forever.
Use indentation inside the loop to make your script easier to read.
You can use break to exit the loop early if needed.
Summary
A while loop repeats commands while a condition is true.
It is useful for repeating tasks until something changes.
Remember to update variables inside the loop to avoid infinite loops.