5 Useful Bash For Loop Examples

Imagine you have a directory filled with thousands of files, and you have been asked to process these files one by one. Sounds quite tedious, right? Well not, if you are using For loops in Bash script. For loop in bash script is a magical tool that can help you automate any repetitive task while efficiently handling those files without breaking a sweat. In this article, we discuss what are for loops in bash with some practical examples to make automation a child’s play.

What is For Loop in Bash Script

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.

Bash For Loop: POSIX Style Syntax

Bash For Loop: POSIX Style Syntax

The POSIX (Portable Operating System Interface) style syntax can be used with POSIX compliant shells like bash and can be used to iterate over a list of files, any sequence, or even the output of other commands. Here is the for loop syntax in bash script:

In the above syntax, here’s what everything means:

Let us now see some practical examples based on the POSIX style for loop:

Example 1: Loop through a Given Range

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.

Example 2: Loop through an Array

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:

Example 3: Loop with Command Substitution

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:

Bash For Loop: C Style Syntax

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:

Example 1: Print Odd Numbers from 1 to 10

In the above snippet:

Here is the output you will get for the above code:

Example 2: Loop through an Array

In the above code:

Here is the output of the above for loop:

Beebom Staff

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.

Add new comment

Name

Email ID

Δ

01

02