Here are some examples of using the while
loop in a Bash shell script:
count=10
while [ $count -gt 0 ]; do
echo "$count"
count=$((count - 1))
done
echo "Done!"
This script will print the numbers 10 through 1, and then print "Done!"
<h2>Example 2: Reading lines from a file</h2>
``` sh
#!/bin/bash
filename="file.txt"
while read -r line; do
echo "$line"
done < "$filename"
This script will read each line from the file file.txt
and print it to the terminal.
while ! ping -c1 google.com &>/dev/null; do
echo "Ping failed. Trying again in 5 seconds..."
sleep 5
done
echo "Ping successful."
This script will repeatedly send a ping request to google.com until it receives a response. If the ping request fails, it will print a message and sleep for 5 seconds before trying again. If the ping request succeeds, it will print a message and exit the loop.
These are just a few examples of using the `while` loop in a Bash shell script. The `while` loop is a powerful and versatile control structure that can be used in a wide variety of situations.