How to Create a While Loop in Bash
A while
loop in Bash is a control structure that allows you to execute a block of commands repeatedly as long as a specified condition is true. This type of loop is particularly useful when the number of iterations is not known in advance, and you want to continue looping until a certain condition is met.
Basic Syntax of the while
Loop
The basic syntax of a while
loop in Bash is as follows:
while [ condition ]
do
# commands to execute while condition is true
done
In this syntax:
condition
is the expression that is evaluated before each iteration. If it evaluates to true, the commands within thedo
block are executed.- The
do
keyword indicates the start of the commands to be executed. - The
done
keyword marks the end of thewhile
loop.
Example of a While Loop
Here’s a simple example of using a while
loop to count down from 5:
#!/bin/bash
# Count down from 5
count=5
while [ $count -gt 0 ]
do
echo "Countdown: $count"
((count--)) # Decrement the count
done
In this example:
- The variable
count
is initialized to 5. - The loop continues as long as
count
is greater than 0. - Inside the loop, it prints the current value of
count
and then decrements it by 1 using((count--))
. - When
count
reaches 0, the loop terminates.
Using a While Loop to Read User Input
You can also use a while
loop to read user input until a specific condition is met. Here’s an example:
#!/bin/bash
# Read user input until they enter "exit"
input=""
while [ "$input" != "exit" ]
do
echo "Enter a command (type 'exit' to quit):"
read input
echo "You entered: $input"
done
In this example:
- The loop continues until the user types "exit".
- Inside the loop, it prompts the user to enter a command, reads the input, and prints it back to the user.
- When the user types "exit", the loop terminates.
Using Break and Continue in While Loops
You can control the flow of a while
loop using the break
and continue
statements:
#!/bin/bash
# Count from 1 to 10, but skip 5
count=1
while [ $count -le 10 ]
do
if [ $count -eq 5 ]; then
((count++)) # Skip the rest of the loop for this iteration
continue
fi
echo "Count: $count"
((count++))
done
In this example:
- The loop counts from 1 to 10.
- If
count
equals 5, it incrementscount
and usescontinue
to skip the rest of the loop for that iteration. - For all other values, it prints the current count.
Conclusion
The while
loop in Bash is a powerful tool for executing commands repeatedly based on a condition. It is particularly useful for scenarios where the number of iterations is not predetermined. By mastering the while
loop, you can create more dynamic and responsive scripts that can handle various conditions and user inputs effectively.