Bash Array Operations
Array operations change an array or report facts about it. Bash can count items, add items and copy a slice.
Count the items
The # symbol with @ gives the item count. The array below holds three colors.
colors=(red green blue)
echo "${#colors[@]}"Add an item
The += form adds one item at the end. The count grows from three to four.
colors=(red green blue)
colors+=(yellow)
echo "${colors[@]}"
echo "${#colors[@]}"Copy a slice
A slice starts at index 1 in this code. It copies the next two items.
colors=(red green blue yellow)
echo "${colors[@]:1:2}"Example
colors=(red green blue)
colors[1]=purple
colors+=(yellow)
echo "${colors[@]}"
echo "${#colors[@]}"
echo "${colors[@]:1:2}"Key points
- Write ${#colors[@]} to count the items in an array.
- Use colors+=(yellow) to add one item at the end.
- Write colors[1]=purple to replace the item at index 1.
- A slice copies a short run of items from an array.
- Write ${colors[@]:1:2} to copy two items starting at index 1.
In this example, the code first replaces green with purple at index 1. It then adds yellow at the end of the array. The prints show all four items, the count 4 and a slice of two items.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line adds yellow at the end of the colors array?