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"
done
This 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
done
This 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]}"
done
This 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\n" "$element"
done
This 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.
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.