Skip to content

Click on each book below to review & buy on Amazon.

As an Amazon Associate, I earn from qualifying purchases.


CompTIA Linux+ XK0-005 - 3.1 - Shell Script Elements: for Loops

In shell scripting, a for loop allows you to iterate over a set of values or elements. It provides a concise and structured way to repeat a block of code for each item in a list or range. For loops are useful for performing repetitive tasks and processing data efficiently.

Basic Syntax

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

for variable in list
do
    # Code to be executed for each iteration
done
  • variable represents the loop variable that takes each value from the list in each iteration.
  • list is a sequence of elements separated by spaces. It can be a list of strings, file names, or a range of numbers.

Example: Iterating over an Array

#!/bin/bash

# Define an array of fruits
fruits=("Apple" "Banana" "Orange" "Mango")

# Iterate over each fruit in the array
for fruit in "${fruits[@]}"
do
    echo "Fruit: $fruit"
    # Perform operations on each fruit
done

In this example, the for loop iterates over each element in the fruits array. The loop variable fruit takes the value of each fruit in each iteration, and the code block within the loop is executed. You can customize the operations within the loop to process each fruit accordingly.

Example: Looping through a Range of Numbers

#!/bin/bash

# Iterate over a range of numbers from 1 to 5
for num in {1..5}
do
    echo "Number: $num"
    # Perform operations using the number
done

In this example, the for loop iterates over a range of numbers from 1 to 5. The loop variable num takes the value of each number in each iteration, and the code block within the loop is executed. You can customize the operations within the loop to process each number according to your requirements.

Conclusion

For loops are powerful constructs in shell scripting that allow you to iterate over a list of values or elements. They provide an efficient way to repeat code blocks for each item in the list. By understanding the basic syntax and examples provided, you can effectively use for loops to automate repetitive tasks, process data, and perform various operations in your shell scripts.


Support DTV Linux

Click on each book below to review & buy on Amazon. As an Amazon Associate, I earn from qualifying purchases.

NordVPN ®: Elevate your online privacy and security. Grab our Special Offer to safeguard your data on public Wi-Fi and secure your devices. I may earn a commission on purchases made through this link.