Bash Shell Script Function Examples

In Bash, you can iterate over an array in several ways. Here are some examples:

  1. Iterate over an array using a for loop:
    my_array=(apple banana cherry)
    for i in "${my_array[@]}"
    do
    echo "$i"
    done

    This will loop through each element in the my_array array and print it to the console.

  2. Iterate over an array using a while loop and the shift command:
    my_array=(apple banana cherry)
    while [ "${#my_array[@]}" -gt 0 ]
    do
    echo "${my_array[0]}"
    shift
    done

    This will loop through each element in the my_array array and print it to the console using the shift command to remove the first element of the array in each iteration.

  3. Iterate over an array using a for loop with an index variable:
    my_array=(apple banana cherry)
    for (( i=0; i<${#my_array[@]}; i++ ))
    do
    echo "${my_array[$i]}"
    done

    This will loop through each element in the my_array array using an index variable i, and print the corresponding element to the console using array indexing.

  4. Iterate over an array using a for loop and the printf command:
    my_array=(apple banana cherry)
    for element in "${my_array[@]}"
    do
    printf "%s\n" "$element"
    done

    This will loop through each element in the my_array array and print it to the console using the printf command with the %s format specifier to print a string.

These are just a few examples of how to iterate over an array in Bash. You can choose the method that works best for your specific use case.

Leave a Comment