0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use While Loop in Bash: Syntax and Examples

In bash, a while loop repeatedly executes a block of code as long as the given condition is true. The syntax is while [ condition ]; do commands; done. This loop is useful for running commands multiple times until a condition changes.
📐

Syntax

The basic syntax of a while loop in bash is:

  • while [ condition ]: Checks the condition before each loop iteration.
  • do: Starts the block of commands to run repeatedly.
  • commands: The commands to execute while the condition is true.
  • done: Ends the loop block.

The condition is usually a test command that returns true or false.

bash
while [ condition ]
do
  commands
 done
💻

Example

This example counts from 1 to 5 using a while loop. It shows how the loop runs commands repeatedly while the condition is true.

bash
count=1
while [ $count -le 5 ]
do
  echo "Count is $count"
  ((count++))
done
Output
Count is 1 Count is 2 Count is 3 Count is 4 Count is 5
⚠️

Common Pitfalls

Common mistakes when using while loops in bash include:

  • Forgetting spaces around square brackets in the condition, e.g., [ $count -le 5 ] must have spaces.
  • Not updating the variable inside the loop, causing an infinite loop.
  • Using incorrect test operators or syntax.

Here is a wrong and right example:

bash
# Wrong: missing spaces and no increment (infinite loop)
count=1
while [$count -le 5]
do
  echo $count
done

# Right: spaces and increment
count=1
while [ $count -le 5 ]
do
  echo $count
  ((count++))
done
📊

Quick Reference

ElementDescriptionExample
while [ condition ]Loop runs while condition is truewhile [ $x -lt 10 ]
doStart commands blockdo
commandsCommands to execute each loopecho $x; ((x++))
doneEnd loop blockdone

Key Takeaways

Use spaces around brackets in the condition: [ condition ].
Update variables inside the loop to avoid infinite loops.
The while loop runs commands repeatedly while the condition is true.
Use (( )) for arithmetic operations inside the loop.
Always close the loop with done.