Bash Shell Script Function Examples
In Bash, you can iterate over an array in several ways. Here are some examples:
- Iterate over an array using a for loop:
my_array=(apple banana cherry) for i in "${my_array[@]}" do echo "$i" doneThis will loop through each element in the
my_arrayarray and print it to the console. - 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 doneThis will loop through each element in the
my_arrayarray and print it to the console using theshiftcommand to remove the first element of the array in each iteration. - 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]}" doneThis will loop through each element in the
my_arrayarray using an index variablei, and print the corresponding element to the console using array indexing. - 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 " "$element" doneThis will loop through each element in the
my_arrayarray and print it to the console using theprintfcommand with the%sformat specifier to print a string.
