How to use for and while loops in bash scripting?
Bash loops are used to repeatedly execute a set of commands until a specified condition is met. There are two main types of loops in Bash: for loops and while loops.
For Loop
The for loop is used to iterate over a range of values or elements in a list. The basic syntax is as follows:
Looping through a range of numbers
This will output:
Looping through elements in an array
This will output:
Looping through files in a directory
This will list all files in the specified directory.
While Loop
The while loop continues to execute a block of code as long as a specified condition is true. The basic syntax is as follows:
Looping until a counter reaches a certain value
This will output the numbers 1 through 5.
Reading input until a specific value is entered
This will keep prompting the user for input until they enter "exit".
Additional Notes:
The for loop is suitable when you know the items to iterate over beforehand, such as iterating through a range of numbers, elements in an array, or files in a directory. On the other hand, the while loop is employed when you want to repeat a block of code based on a condition that may change during execution, like looping until a counter reaches a certain value or until a specific input is entered.
Both loops can be nested within each other to handle more complex scenarios. Additionally, the break statement can be used to exit a loop prematurely, while the continue statement allows you to skip the current iteration and move on to the next one. These features provide flexibility and control in automating repetitive tasks in Bash scripting.
Conclusion
Bash provides two main loops: the for loop, suitable for iterating over known items like numbers or array elements, and the while loop, ideal for repeating code based on changing conditions. Both loops support nesting, and you can use the break statement to exit prematurely or continue to skip the current iteration.