Shell Script While Loop Examples
Here are a few examples of while loops in shell scripts:
Example 1: Counting from 1 to 10
#!/bin/bash
count=1while [ $count -le 10 ]
do
n echo $count
n count=$((count+1))
doneThis script initializes a variable called count to 1 and then uses a while loop to print the value of count and increment it by 1 until it reaches 10.
Example 2: Reading lines from a file
#!/bin/bashwhile read line
do
n echo $line
done < file.txtThis script uses a while loop to read lines from a file called file.txt and print each line to the terminal.
Example 3: Generating random numbers
#!/bin/bashwhile true
do
n random_number=$RANDOM
n echo $random_number
n sleep 1
doneThis script uses a while loop to generate a new random number using the built-in $RANDOM variable and print it to the terminal every second.
In each of these examples, the while loop continues to execute as long as the condition in the while statement is true. When the condition becomes false, the loop terminates and the script continues to execute the next command after the done keyword.
