Bash Array Slicing
Array slicing takes a part of an array. It uses an offset and a length inside the expansion.
Take three items from the middle
The slice starts at offset 1 and takes 3 items. The output shows the middle three colours, in order.
arr=(red green blue yellow purple)
echo "${arr[@]:1:3}"Count back from the end
A negative offset counts back from the end. The space before -2 keeps Bash from reading :- as a default value.
arr=(red green blue yellow purple)
echo "${arr[@]: -2}"Indices, array length, and element length
The indices line lists 0 to 4. The next line counts 5 items, and the last line counts 5 letters in green.
arr=(red green blue yellow purple)
echo "${!arr[@]}"
echo "${#arr[@]}"
echo "${#arr[1]}"Example
arr=(apple banana cherry date elderberry fig)
echo "First two: ${arr[@]:0:2}"
echo "Last one: ${arr[@]: -1}"
echo "Total: ${#arr[@]}"
echo "Second fruit letters: ${#arr[1]}"Key points
- Slice: ${arr[@]:offset:length} takes items from an offset for a length.
- Offset: the first item sits at offset 0, not 1.
- Omitted length: a slice with no length runs to the end of the array.
- Negative offset: a negative offset counts back from the end of the array.
- Space before a negative offset: write ${arr[@]: -2}, because :- is read as a default-value operator.
- Indices: ${!arr[@]} lists the index of each item.
- Array length: ${#arr[@]} counts items in the array.
- Element length: ${#arr[0]} counts characters in one item, not items in the array.
In this example, the array holds six fruits. The first echo takes two fruits from offset 0. The second echo takes the last fruit with a negative offset. The third echo prints the item count. The last echo prints the letter count of the second fruit.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does ${arr[@]: -2} print?