How to use loops (for, while) in a Bash script?

In Bash scripting, you can use both for loops and while loops to execute commands repeatedly. Here's a brief explanation of each loop and how to use them:

  1. For loop: The for loop allows you to iterate over a sequence of values, such as elements in an array or a range of numbers.

Syntax:

for variable in [sequence] do # commands to be executed done

Example:

for i in {1..5} do echo "Number: $i" done

This will print numbers from 1 to 5.

  1. While loop: The while loop executes a block of code as long as a certain condition is true.

Syntax:

while [ condition ] do # commands to be executed done

Example:

counter=1 while [ $counter -le 5 ] do echo "Counter: $counter" ((counter++)) done

This will print the value of the counter variable from 1 to 5.

You can also use other conditional statements like break to exit a loop prematurely or continue to skip the current iteration and move to the next one.

By combining loops with conditional statements and variables, you can create powerful scripts to automate tasks in Bash.