In this tutorial, you will learn how to write, understand, and implement BASH While Loops. This powerful tool can automate repetitive tasks, making your programming more efficient.
Step 1: Introduction to BASH While Loops
A while loop in BASH iterates over a block of code as long as a certain condition is true.
while [ condition ]
do
command1
command2
...
donePractice Exercise
Write a while loop that counts from 1 to 5, printing each number.
Show Solution
COUNT=1
while [ $COUNT -le 5 ]
do
echo $COUNT
((COUNT++))
doneStep 2: Using Variables in BASH While Loops
Variables can be used within the loop to keep track of state. The variable can be changed within the loop, influencing the overall flow.
COUNT=1
while [ $COUNT -le 5 ]
do
echo $COUNT
((COUNT++))
donePractice Exercise
Create a while loop that counts backwards from 10 to 1.
Show Solution
COUNT=10
while [ $COUNT -ge 1 ]
do
echo $COUNT
((COUNT--))
doneStep 3: Breaking Out of a BASH While Loop
You can use the break command to exit a loop before the condition becomes false.
COUNT=1
while [ $COUNT -le 5 ]
do
if [ $COUNT -eq 3 ]
then
break
fi
echo $COUNT
((COUNT++))
donePractice Exercise
Write a while loop that counts from 1 to 10 but breaks and exits when it reaches 5.
Show Solution
COUNT=1
while [ $COUNT -le 10 ]
do
if [ $COUNT -eq 5 ]
then
break
fi
echo $COUNT
((COUNT++))
doneStep 4: Infinite BASH While Loop
An infinite while loop continues indefinitely because its condition always remains true. Use ctrl + c to exit.
while :
do
echo 'This is an infinite loop. Press ctrl + c to exit.'
donePractice Exercise
Write an infinite while loop that prints 'Still running...' every second.
Show Solution
while :
do
echo 'Still running...'
sleep 1
doneStep 5: BASH While Loop with User Input
You can create interactive scripts by using read to get user input during the execution of a while loop.
while :
do
echo 'Enter a number (or "quit" to exit):'
read INPUT
if [ $INPUT = 'quit' ]
then
break
fi
echo 'You entered: ' $INPUT
donePractice Exercise
Create a while loop that asks the user to guess a secret number. If the guess is correct, break the loop.
Show Solution
SECRET=7
while :
do
echo 'Guess the secret number (or type "quit" to exit):'
read GUESS
if [ $GUESS = 'quit' ]
then
break
elif [ $GUESS -eq $SECRET ]
then
echo 'Congratulations! You guessed correctly.'
break
else
echo 'Sorry, try again.'
fi
doneSign in to take Cornell notes on this lesson — they save automatically and stay with your account.