Shell Script While Loop: Syntax & Usage
In a shell script, a while loop is used to repeatedly execute a certain code block until a specified condition is no longer met. The syntax is as follows:
while [ condition ]
do
# code to be executed
done
In the syntax above, the condition is the condition that needs to be evaluated. The code block within the loop will only be executed when the condition is true. The code block within the loop can contain any shell commands and statements.
After executing the code block in each iteration, the value of the condition is checked again. The loop will continue only if the condition is true, otherwise it will terminate.
Here is an example illustrating the usage of a while loop.
#!/bin/bash
count=0
while [ $count -lt 5 ]
do
echo "Count: $count"
count=$((count+1))
done
The above code will print numbers from 0 to 4, with each number on a separate line.