Looping is an inherent art, which can make your work simpler and help you automate repetitive tasks with relative ease.

Imagine a situation wherein you need to update a series of numbers or text, and instead of doing it manually, you have the system do it for you. This is the power of looping and the benefits it brings to the table for you.

Loops, as a function, are available in almost every programming language; Linux’s Bash is no exception to this rule.

Here's a guide explaining how you can use the for loop in a shell script.

The for Loop Structure

Using the for loop in shell scripts is reasonably straightforward, and you can manipulate the structure to achieve different goals.

The basic structure is as follows:

        for item in [LIST]

do

 [COMMANDS]

done

With a loop, you can cycle through numeric and character values, depending on the need of the hour.

Related: How to Use Loops in JavaScript

Here's the structure of a for loop in a shell script:

        for VARIABLE in 1 2 3 4 5 .. N
do
   command1
   command2
   commandN
done

You can define the number of iterations in the first line. This way, you'll mention the starting value and the ending value.

The number of iterations is determined by the values you specify, while the code following the do statement is the resulting loop value.

Creating and Running for Loops in Linux Bash

Open the Linux terminal to start writing code.

A text editor is used to store the shell script, which prints the desired results when executed. For illustration purposes, the commands in this guide are written in the Nano text editor.

Type nano in the terminal command line to open the text editor, followed by the shell script name.

        nano ForLoops.sh
    

You can change the name of the shell script to whatever you like. The extension is sh, since you'll be storing a shell script.

In this section, the following codes will demonstrate how you can print integer values differently. To use a for loop in a shell script to print integers, you can try some of these code examples.

1. Loop Code to Print a Set of Numbers

Once the editor opens, it's time to write the code.

        #!/usr/bin/bash

for i in 1 2 3

do

       echo "Current # $i"

done
Linux terminal interface

Output:

Linux terminal interface

Where:

  • i = variable name to store the iterated values
  • 1 2 3 = number of times the for loop in shell script iterates
  • do = command to perform a certain set of actions
  • echo = print the results defined alongside
  • done = end of the loop

Save the code in the text editor by pressing Ctrl + X. Save and exit the script.

Related: How to Use For, While, and Do While Loops in Java With Examples

Before executing the code, you have to change the shell script's permissions.

Enter chmod +x followed by your shell script file name:

        chmod +x Forloops.sh
    

Once the permissions are granted, run the for loop in your shell script by typing in the following:

        ./Forloops.sh
    

The output will print in the terminal window.

2. Alternate Way to Print a Set of Numbers

There are alternate ways to define a for loop in a shell script. You can also specify the starting and ending value of the loop's iterations using curly brackets.

Here's the code structure:

        for i in {1..3} # a for loop defines a variable and how many iterations you want to make through a loop

do

       echo "Current # $i: Example 2"

done
Linux terminal interface

The loop will run three times, and the values will be printed in the following manner:

Linux terminal interface

3. Loop Code Using Step Values

You can define the step values in your loop if you want to move nonsequentially through the iterations. Depending on the value specified, the output will have a fixed gap.

For example:

        for i in {1..10..2}

do

       echo "Number = $i"

done

Where:

  • i = variable to store the iterations
  • 1..10 = number of iterations to run the loop
  • 2 = step value
  • do = command to print the output
  • echo = print command
  • done = exit command for the loop
Linux terminal interface

Output:

Linux Terminal interface

The output has a difference of two, which was specified in the step statement.

For loops in shell scripting isn't restricted to just integers. In Bash, you can use a for loop to effectively iterate through characters and string values.

1. Looping Through Strings

Here's a basic example of how you can loop through some string values (defined in the for statement):

        for name in  John Jack Mary

do

 echo "My name is $name"

done

Where:

  • name = variable to store the string values
  • do = command to print the output
  • echo = print command
  • done = exit command for the loop
Linux terminal interface

Output:

Linux terminal interface

This for loop will iterate three times, as there are only three string values specified in the for statement.

2. Looping Through Strings With Conditions

What if you want to pass some logical conditions to terminate the loop mid-way? For this purpose, you can use logical statements such as the IF statement. The IF statement controls how the loop will work and what output will print as a result.

        for element in Hydrogen Helium Lithium Beryllium; do



 if [[ "$element" == 'Lithium' ]]; then



   break



 fi



 echo "Element: $element"



done



echo 'All Done!'
Using-conditional-statements-in-Linux-Bash-1

Related: How to Use Loops With Lists in PythonAs soon as the element's value equals Lithium, the loop terminates, and the output prints. The loop runs until the condition is no longer met.

Since Lithium is third in the list of values, the loop will run for two iterations before it prints the final output All Done!.

Linux terminal interface

Running Loops in Linux Bash

Loops are an essential part of the Linux shell structure, which can greatly enhance the function of Linux scripts.

If you have to print repetitive outputs, there is nothing better than loops within Bash scripts. As we mentioned earlier, loops are available in nearly every programming language, and Python is no exception. Cut out repetition and live by the DRY (Don't Repeat Yourself) code.