Mastering Shell Scripting, Understanding For Loops in Bash

Authors

When it comes to automating repetitive tasks, shell scripting is a powerful tool.

One of the most fundamental concepts in shell scripting is the for loop.

In this guide, we'll cover everything you need to know about for loops in shell scripting.

For Loops In Shell Scripting

A for loop is a control structure that allows you to repeat a set of commands for a specified number of times.

The syntax of a for loop in shell scripting is as follows:

for variable in list
do
    # Commands to be executed
done

The variable is a user-defined variable that is used to store each item in the list during each iteration of the loop.

The list is a sequence of items that the loop will iterate over.

The commands to be executed are the set of instructions that will be executed during each iteration of the loop.

Let's take a look at a simple example of a for loop in action:

#!/bin/bash

for i in 1 2 3 4 5
do
    echo $i
done

In this example, we're using a for loop to print the numbers 1 through 5 to the console.

The variable i is used to store each item in the list (1 through 5) during each iteration of the loop.

The echo command is used to print the value of i to the console during each iteration.

Output:

1
2
3
4
5

You can also use a for loop to iterate over the contents of a directory. For example:

#!/bin/bash

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

In this example, the variable file is used to store each file in the directory /path/to/directory during each iteration of the loop.

The echo command is used to print the name of each file to the console during each iteration.

For loops can also be used to iterate over a range of numbers. For example:

#!/bin/bash

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

In this example, we're using a for loop to print the numbers 1 through 5 to the console using brace expansion.

The variable i is used to store each item in the list (1 through 5) during each iteration of the loop.

The echo command is used to print the value of i to the console during each iteration.

Output:

1
2
3
4
5

You can also use a for loop to iterate over the output of a command. For example:

#!/bin/bash

for file in $(ls /path/to/directory)
do
    echo $file
done

In this example, the variable file is used to store each file in the directory /path/to/directory during each iteration of the loop.

The ls command is used to generate a list of files in the directory, and the output of the ls command is used as the list for the for loop.

Conclusion

In conclusion, for loops are a powerful tool in shell scripting that allow you to automate repetitive tasks.

Whether you're iterating over a list of files, a range of numbers, or the output of a command, for loops can save you time and effort.

TrackingJoy