Jannah Theme License is not validated, Go to the theme options page to validate the license, You need a single license for each domain name.
Linux

A Guide to Using Bash For Loops in Linux with Examples

Introduction

Bash is the language that your computer can understand easily. This language runs on commands, which, when run in series, are eventually known as Bash scripting. A loop comes into the picture when a user wants to repeat a set of instructions multiple times. Loops in Bash scripting are like repeating a set of instructions until you achieve a particular goal. Imagine you have a task you want to do over and over again, like saying “hello” five times. A Linux Bash loop can pave the way for such an operation without taking much time.

This article will serve as the perfect guide for you to get the loop deployed through bash. We have included simple yet effective examples of bash for loop in this piece to get a deeper understanding.

Bash Scripting – For Loop

Bash is a powerful scripting language used in the Linux environment to automate tasks and perform various operations on the system. With its ability to contain loops and other constructs, Bash provides users with a flexible and efficient way to interact with their Linux-based systems through commands and scripts. By utilizing Bash in Linux for loop, you can manage your systems more effectively and save time by automating repetitive tasks. Read the content below to learn about the three main loop types.

  1. For loops: When you want to repeat a task a certain number of times, a “for loop” comes in handy.
  2. While loops: This type is used to achieve the result till a certain condition remains true, like eating ice cream while it’s sunny. So, the “while loop” is slightly different from the “for loop” in terms of conditional match.
  3. Until loops: The third type, which is the “until loop,” is quite different from both the above-mentioned types. Here, you can instruct the computer to keep acting until a particular situation arises. For example, you can eat ice cream from when it’s sunny until it starts to rain.

Let’s move forward toward a more detailed approach to “for loop” with uncomplicated examples. 

Bash For Loop Examples

1. Individual Items

Through this approach, the client can easily work on various individual items a repeated number of times. The syntax of the command is given below. 

Bash For Loop Examples

In the above syntax, the variable is fruit, and the individual items are orange, banana, and apple. The command will instruct the computer to keep performing the task until all three individual items are matched. The phrase “I like $fruit” will be printed during each repetition. 

Bash For Loop Examples

2. Range

The range loop example emphasizes performing repetitive tasks inside a particular range. Check out the below syntax for more clarity. 

Bash For Loop Examples

The variable ‘number’ is set to hold values from 1 to 5. The loop runs five times, once for each number in the range. During each iteration, the ‘echo’ command prints “Number: [current number]”. The loop updates the ‘number’ variable to the next value in the range until it reaches 5. Once all the numbers in the range are processed, the loop ends.

Bash For Loop Examples

3. Range with Increment

This example is based on the increment system, wherein you will be able to instruct the computer to increase the value systematically in a Bash for loop.

Bash For Loop Examples

The loop command will instruct the computer to print numbers from 3 to 15 with a step of 3 until it reaches 15.

Bash For Loop Examples

4. The seq Command

In the below seq command syntax, we will use Bash in Linux for loop.

Bash For Loop Examples

The line “#!/bin/bash ” has been used to enable the Bash script. The difference between the “range with increment” and “seq command” lies in the placement of the gap value.

Bash For Loop Examples

Here, you can see that the result is almost the same.

5. C-Style

A C-style loop is used when the user wants to create precise repetition on a numerical range. The following command syntax will offer a deeper insight into the C-style loop. 

Bash For Loop Examples

This code initializes a loop with three parts:

  • Setting the initial value of the variable i to 0
  • Specifying that the loop will continue as long as i is less than 5
  • Increasing the value of i by one after each iteration

During each iteration, the command ‘echo “Iteration: $i”‘ will print the current value of i. The code is written in simple language to make it easy to understand, and the information is presented in a logical order to help the reader follow along.

Bash For Loop Examples

6. Infinite Loops

Many times, a user might want the program to run endlessly. This type of loop does not have a termination command or situation. An important point to note here is that both an infinite loop and a while loop can theoretically run indefinitely, executing their block of code repeatedly without an inherent endpoint. The only difference lies in their termination command, which is present in the “while loop” and missing in the “infinite loop.” The below command syntax is programmed to run the loop without any stoppage.

Bash For Loop Examples

7. Break

This type is used to abruptly exit the loop when a certain condition is met. This is similar to a “while loop”; the difference lies in their method of termination.

for number in {1..10}do
    if [ $number -eq 5 ]  # Checks if the current number is equal to 5
    then
        break            # Exits the loop if the condition is met (number equals 5)
    fi
    echo "Number: $number"  # Prints the current number if the condition is not met
Done

In the above command, the following things have happened:

  • Loop: It counts from 1 to 10.
  • Condition: It checks if the number is 5.
  • break: If it finds 5, it stops counting immediately.
  • echo: It says the number aloud for each count, except when it finds 5.

8. Continue

The continue command in a loop skips the code after it for the current iteration and moves to the next one. Take a look at the below syntax.

Bash For Loop Examples

You can see that the above command has instructed the system to display numbers from 1 to 5, but continue the code by skipping the digit 3.

Bash For Loop Examples

9. Strings

This type goes by its name. A Bash for-loop can be performed on a string of words in a sentence without listing each word of the sentence. See the following example:

Bash For Loop Examples

The above command will list out all the words of the specified sentence in the following manner.

Bash For Loop Examples

10. Files

You can use a Bash script for loop to perform actions on files located close to each other alphabetically, by date, or by some other criterion. This involves iterating through the files and performing actions based on specific conditions, such as renaming, copying, or deleting them. Combining a for loop with proximity searches allows you to automate actions or modifications on files that meet those specific conditions. This approach offers an efficient and selective way to process files based on predefined criteria.

11. Command Substitution

Command substitution involves using the output of a command as a value or list of values. In a for loop, command substitution can generate a list of elements for iteration. 

Bash For Loop Examples

14. Command-Line Arguments

Think of command-line arguments as pieces of information you give a program when you run it in the terminal. A Bash for loop helps you go through these pieces of information one by one.

Conclusion

Loops are a helpful tool for automating repetitive tasks and achieving desired outcomes in programming. They can save a lot of time and effort by performing the same task multiple times until a specific condition is met. Bash for loops is a powerful feature in Linux scripting that allows you to automate tasks and perform repetitive operations efficiently. 

The ‘for’ loop, along with other types like ‘while’ and ‘until’, enables you to repeat actions based on conditions or predefined values. The loops can be used in various scenarios, like iterating through individual items, numeric ranges, strings, files, and command outputs. This versatility makes Bash loops a valuable tool for managing tasks in the Linux environment. Whether you need to perform operations on files or process command-line arguments, Linux Bash loops provide an efficient and manageable way to streamline and automate tasks.

Arpit Saini

He is the Director of Cloud Operations at Serverwala and also follows a passion to break complex tech topics into practical and easy-to-understand articles. He loves to write about Web Hosting, Software, Virtualization, Cloud Computing, and much more.

Related Articles