What is For Loop in Bash Script
For loop is a control structure that is used to perform repetitive tasks or execute a bunch of commands a specific number of times. With for loop, you can iterate through numbers, lists, files, or even directories.
In the above syntax, here’s what everything means:
Let us now see some practical examples based on the POSIX style for loop:
In the above snippet, the $(seq 1 5) part is used to generate a list of integers from 1 to 5. It will then loop over the list one by one and then each value will get printed on a new line.
An array is a data structure that is used to contain multiple data of different types. In the above snippet:
Here is the output we will get from the above commands:
The way command substitution works is, the command gets first executed and then the for loop will iterate through the entire output of the command. The command to be iterated upon is placed inside “$()“. In the above snippet:
The output for the for loop with command substitution as demonstrated in the above example would be:
The C style syntax suits users who are more accustomed to the for loop syntax in other languages like C, C++, Java, JavaScript, etc. Here is the basic syntax to the C style for loop:
In the above syntax:
Let us now see some practical examples based on the C style for loop:
In the above snippet:
Here is the output you will get for the above code:
In the above code:
Here is the output of the above for loop:
Bringing the latest in technology, gaming, and entertainment is our superhero team of staff writers. They have a keen eye for latest stories, happenings, and even memes for tech enthusiasts.