When you start learning Bash scripting, one of the most powerful tools you’ll come across is the bash while loop. It allows you to repeat tasks until a condition changes. Whether you want to count numbers, process a file, or keep a program running until you stop it, the while
loop is the perfect choice.
In this article, we’ll break it down into simple terms with examples anyone can follow.
A bash while loop is a structure that keeps running a set of commands as long as a condition remains true. Once the condition becomes false, the loop stops.
The basic structure looks like this:
while [ condition ]
do
# commands to run
done
condition
→ The check that decides if the loop continuesdo
→ Marks the start of commandsdone
→ Marks the end of commandsLet’s look at a simple script:
#!/bin/bash
i=1
while [ $i -le 5 ]
do
echo "Number: $i"
i=$((i+1))
done
Here’s what happens:
#!/bin/bash
is called a shebang. It tells the system to use Bash to run the script. i
starts at 1[ $i -le 5 ]
means “keep looping while i is less than or equal to 5”i
, then increases it by 1i
becomes 6, the condition fails and the loop endsOne of the most common uses of a bash while loop is reading files.
#!/bin/bash
filename="mydata.txt"
while IFS= read -r line
do
echo "$line"
done < "$filename"
Explanation:
IFS= read -r line
→ Reads one line at a time safely into the variable line
done < "$filename"
→ Redirects the loop to take input from the file instead of the keyboardThis method is reliable because it handles spaces and special characters correctly.
Sometimes you want a loop to run forever until you stop it manually. You can do this with a bash while loop:
#!/bin/bash
while :
do
echo "Still running..."
sleep 1
done
:
command always returns trueCtrl+C
This is handy for monitoring or background tasks.
#!/bin/bash
i=1
while :
do
echo "i is $i"
if [ $i -ge 5 ]
then
echo "Stopping loop"
break
fi
(( i++ ))
done
Even though the loop is infinite, break
forces it to end when i
reaches 5.
#!/bin/bash
i=0
while [ $i -lt 10 ]
do
(( i++ ))
if (( i % 2 != 0 ))
then
continue
fi
echo "Even number: $i"
done
In this case, the loop skips odd numbers and only prints even ones.
The bash while loop is perfect when you don’t know how many times a task will repeat. Some benefits include:
break
and continue
for controlWhether you’re a beginner or advanced user, learning while loops will save you time and effort in Bash scripting.
The bash while loop may look technical at first, but once you understand its structure, it becomes one of the easiest tools to automate repetitive tasks.
You now know:
-le
inside loops#!/bin/bash
)break
and continue
Mastering this will give you a solid foundation in Bash scripting and make your scripts more powerful and reliable.