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:

Here’s an example that uses a while loop to count from 1 to 10:

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.

Leave a Reply

Your email address will not be published.