Array Iteration Techniques and Examples
In addition to the basic looping techniques covered in the previous section, shell provides several other ways to iterate over array elements. These techniques can be useful in different scenarios, depending on your specific requirements.
Iterating with select
The select
statement in shell can be used to create a menu-driven interface for interacting with array elements:
my_array=(apple banana cherry)
select fruit in "${my_array[@]}"; do
echo "You selected: $fruit"
break
done
This will output a numbered list of the array elements, and the user can select an item by entering the corresponding number.
Parallel Iteration with zip
The zip
command can be used to iterate over multiple arrays in parallel. This is useful when you need to perform the same operation on corresponding elements from different arrays:
fruits=(apple banana cherry)
prices=(1.99 2.50 3.25)
for fruit, price in $(zip "${fruits[@]}" "${prices[@]}"); do
echo "$fruit costs \$${price}"
done
This will output:
apple costs $1.99
banana costs $2.50
cherry costs $3.25
You can also use shell array operations to filter and transform array elements. For example, to create a new array containing only the even-indexed elements from the original array:
my_array=(apple banana cherry date elderberry)
even_array=("${my_array[@]:0:1}" "${my_array[@]:2:1}" "${my_array[@]:4:1}")
echo "${even_array[@]}" ## Output: apple cherry elderberry
Or, to convert all elements to uppercase:
my_array=(apple banana cherry)
upper_array=("${my_array[@]^^}")
echo "${upper_array[@]}" ## Output: APPLE BANANA CHERRY
These techniques allow you to manipulate array data in powerful and flexible ways, making them valuable tools in your shell programming arsenal.