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:

for variable in list do # commands to be executed done

Looping through a range of numbers

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

This will output:

1 2 3 4 5

Looping through elements in an array

fruits=("apple" "banana" "orange") for fruit in "${fruits[@]}" do echo $fruit done

This will output:

apple banana orange

Looping through files in a directory

for file in /path/to/directory/* do echo $file done

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:

while [ condition ] do # commands to be executed done

Looping until a counter reaches a certain value

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

This will output the numbers 1 through 5.

Reading input until a specific value is entered

input="" while [ "$input" != "exit" ] do echo "Enter a value (type 'exit' to end):" read input echo "You entered: $input" done

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.