Combining While Loops with Other Control Structures
While while
loops are powerful on their own, they can become even more versatile when combined with other control structures in Bash. By integrating while
loops with constructs like if-then-else
, for
loops, and case
statements, you can create complex and dynamic Bash scripts that can handle a wide range of scenarios.
Combining while
Loops with if-then-else
Using if-then-else
statements within a while
loop allows you to add conditional logic and make decisions based on the current state of the loop.
#!/bin/bash
read -p "Enter a number: " num
while [ "$num" -lt 1 ] || [ "$num" -gt 10 ]; do
if [ "$num" -lt 1 ]; then
echo "Number must be greater than or equal to 1."
else
echo "Number must be less than or equal to 10."
fi
read -p "Enter a number between 1 and 10: " num
done
echo "You entered: $num"
In this example, the if-then-else
statement inside the while
loop checks the value of $num
and provides appropriate feedback to the user until a valid number is entered.
Combining while
Loops with for
Loops
You can also use a for
loop within a while
loop to iterate over a set of values or perform a specific number of iterations.
#!/bin/bash
read -p "Enter a number: " num
while [ "$num" -gt 0 ]; do
echo "Countdown: $num"
for ((i = 0; i < 3; i++)); do
echo " Iteration $i"
done
((num--))
done
echo "Blast off!"
In this example, the outer while
loop decrements the value of $num
until it reaches 0, while the inner for
loop executes three iterations for each value of $num
.
Combining while
Loops with case
Statements
Using a case
statement within a while
loop can help you handle multiple conditions or options within the loop.
#!/bin/bash
read -p "Enter 'start', 'stop', or 'quit': " command
while [ "$command" != "quit" ]; do
case "$command" in
start)
echo "Starting the process..."
;;
stop)
echo "Stopping the process..."
;;
*)
echo "Invalid command. Please try again."
;;
esac
read -p "Enter 'start', 'stop', or 'quit': " command
done
echo "Exiting the script."
In this example, the case
statement inside the while
loop handles different user commands until the user enters "quit" to exit the loop.
By combining while
loops with other control structures, you can create more powerful and flexible Bash scripts that can handle a wide range of tasks and requirements.