Logo

Master the Loop: Your Essential Guide to Bash While Loops

Tired of repetitive tasks in your scripts? The Bash `while` loop is your solution! It executes a block of code repeatedly as long as a specified condition remains true. Think of it as saying, "While this condition holds, keep doing this!".

Here's the basic syntax:

```bash
while [ condition ]
do
# Code to execute
done
```

The `condition` can be anything you can test in Bash, like comparing numbers, checking file existence, or evaluating the output of a command. The `do` and `done` keywords mark the beginning and end of the loop's body.

For example, to print numbers 1 to 5:

```bash
i=1
while [ $i -le 5 ]
do
echo $i
i=$((i+1))
done
```

This loop continues as long as `$i` is less than or equal to 5. Inside the loop, we print the value of `$i` and increment it by 1. Mastering `while` loops unlocks powerful automation in your Bash scripting.

See all content
Top Picks

Subscribe now and never miss an update!

Subscribe to receive weekly news and the latest tech trends

Logo
1 345 657 876
nerdy-mind 2025. All rights reserved