Sling Academy
Home/DevOps/How to Use ‘for’ Loop in Bash Scripting

How to Use ‘for’ Loop in Bash Scripting

Last updated: January 29, 2024

Introduction to Bash ‘for’ Loops

One of the fundamental concepts in any programming language is the loop. It allows us to execute a block of code multiple times, which is especially handy for repetitive tasks. In bash scripting, one of the most commonly used loop constructs is the ‘for’ loop. This tutorial will walk you through the basics and intricacies of for loops in bash.

Basic Syntax of ‘for’ Loop

The basic structure of a for loop in bash is as follows:

for VARIABLE in ITEM_1 ITEM_2 ... ITEM_N
do
    COMMAND1
done

Let’s break this down:

  • VARIABLE: A placeholder that will hold each value in a list or an array sequentially.
  • ITEM_1 … ITEM_N: A sequence of items that the VARIABLE will iterate through.
  • The do keyword initiates the cycle that will run once for each item.
  • COMMAND1: The command that will execute for each item. It can be any valid bash command or script.
  • Finally, the loop iteration ends with done.

Here’s a practical example:

for fruit in apple banana cherry
do
    echo "I like $fruit!"
done

This simple loop will print out a statement for each fruit item listed.

Looping Over a Range of Numbers

You can loop over a range of numbers by using the ‘seq‘ command inside the for loop or by using brace expansion.

Here is how you do it using seq:

for number in $(seq 1 10)
do
    echo "Counting... $number"
done

And here is the same loop using brace expansion:

for number in {1..10}
do
    echo "Counting... $number"
done

Both code snippets will count from 1 to 10, outputting each number on a new line.

Iterating Over Array Elements

If you have an array, you can iterate over its elements like so:

fruits=(apple banana cherry)
for fruit in "${fruits[@]}"
do
    echo "Fruit: $fruit"
done

The notation ${fruits[@]} indicates that each element of the array fruits will be passed to the loop.

Iterating Over Files and Directories

The for loop can also be used to easily loop through files and directories.

To process each .txt file in a directory, you can use:

for file in *.txt
do
    echo "Processing $file"
done

This will match all files ending with .txt in the current directory, processing each one in turn.

Nested for Loops

Nested loops are loops within loops, and bash supports them readily. Here’s an example of a nested for loop:

for outer in 1 2 3
do
    for inner in a b c
do
        echo "Outer: $outer; Inner: $inner"
done
done

This will create a combination of every element from the first loop with every element from the second loop.

Using the C-Style for Loop

While less common, you can use a C-style for loop in Bash, which looks like this:

for ((i = 0; i < 10; i++))
do
    echo "C-style counting: $i"
done

This style is familiar to those with a background in languages like C or Java.

Best Practices and Tips

  • Quote your variables to prevent unwanted word splitting, especially when dealing with strings that could potentially contain spaces.
  • Prefer brace expansion or seq with caution depending on your script’s portability requirements. Brace expansion is a feature of bash, while seq is an external program that might not be installed on every system.
  • When using wildcards (e.g., *.txt), be aware of the potential for no files to match the pattern. You might want to include additional checks before processing files.
  • For more complex loops, consider readability. If your loop gets too complicated, it could be a sign to refactor your script or to use functions.

Conclusion

In this tutorial, we covered the use of for loops in bash scripting, including syntax, examples, and best practices. You are now equipped to implement for loops in your own scripts effectively. Happy scripting!

Next Article: How to use ‘do-while’ loop in Bash scripting

Previous Article: How to use if-then statement in Bash scripting

Series: Linux Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide