While Loop Bash
In Bash, the while
loop is used to execute a block of commands repeatedly as long as a certain condition is true. The basic syntax is:
2 3 4 5 |
while condition do # commands to be executed done |
Here’s an example that uses a while
loop to count from 1 to 10:
2 3 4 5 6 7 8 9 10 |
# Initialize the counter variable counter=1 while [ $counter -le 10 ] do echo $counter # Increment the counter ((counter++)) done |
This will print the numbers from 1 to 10, one per line.
The condition
in the while
loop can be any command that returns a boolean value (true or false). In the example above, the condition [ $counter -le 10 ]
tests whether the value of counter
is less than or equal to 10. As long as this condition is true, the loop will continue to execute.
It’s important to include a way to update the value of the condition variable inside the loop, otherwise the loop will become infinite. In the example above, the ((counter++))
statement increments the value of counter
by 1 each time the loop iterates.
You can also use the break
statement to exit a while
loop prematurely, and the continue
statement to skip the rest of the current iteration and move on to the next one.
Recent Comments