About 148,000 results
Open links in new tab
  1. 123

    In Bash, the for loop is used to iterate over a list of items, similar to the foreach loop in other programming languages. Although Bash does not have a built-in foreach loop, the for loop can achieve the same functionality.

    Example: Iterating Over Array Elements

    #!/bin/bash

    # Declare an array with elements
    my_array=("apple" "banana" "cherry" "date")

    # Iterate over each element in the array using a for loop
    for element in "${my_array[@]}"
    do
    echo "Fruit: $element"
    done

    This script will output each element of the array:

    Fruit: apple
    Fruit: banana
    Fruit: cherry
    Fruit: date

    Important Considerations

    Handling Files with Special Characters

    When dealing with files that have special characters, spaces, or newlines, use the find command with xargs to handle them safely1.

    find /path/to/dir -type f -print0 | xargs -0 -I {} echo "Processing file: {}"

    Reading Files Line by Line

    For reading files line by line, use a while loop instead of a for loop2.

    Was this helpful?

    See results from:

  2. 9 Examples of for Loops in Linux Bash Scripts - How-To Geek

  3. Question & Answer
  4. Bash foreach loop - Stack Overflow

  5. Bash For Loop Examples - nixCraft

  6. Iterate Through a Bash Array Using “foreach” Loop [5 …

    Apr 17, 2024 · This article shows how to iterate over Bash arrays using a for loop to represent the behavior of the foreach loop. It shows 5 different examples of printing the array items, array length including array indices, and advanced …

  7. Bash Foreach: Mastering Loops with Ease

  8. How Can I Use Foreach Loops in Bash Script? - Linux …

    Dec 1, 2023 · This guide will walk you through the basics to advanced usage of the ‘foreachloop in Bash. We’ll cover everything from simple loops to more complex iterations, as well as alternative approaches and common issues you …

  9. Bash For Loop Array: Iterate Through Array Values

    3 days ago · Learn how to declare and use arrays in bash with for loop syntax. See examples of indexed and associative arrays, printing, and iterating over keys and values.

  10. Everything You Need to Know About Bash For Loops in Linux

  11. How do I write a 'for' loop in Bash? - Stack Overflow

  12. Some results have been removed