Bash While Loop Examples

www‮l.‬autturi.com
Bash While Loop Examples

Here are some examples of using the while loop in a Bash shell script:

Example 1: Counting down from 10 to 1

``` sh #!/bin/bash

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.

Example 3: Repeating a command until it succeeds

``` sh #!/bin/bash

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.
Created Time:2017-10-16 14:38:39  Author:lautturi