Array append, slice and unset
Use items+=(value) to append to an indexed array; the first new index is one greater than the largest assigned index, or zero for an empty array. unset 'items[1]' removes that element without renumbering other indices. Quote the entire operand passed to unset to prevent filename expansion. "${items[@]:offset:length}" selects a run of existing elements of an indexed array starting at an index offset; gaps are skipped and length counts selected elements, not index positions. Use nonnegative offsets and lengths for these introductory examples. A negative offset needs separating whitespace to avoid confusion with default-value syntax. To reset an indexed array while retaining its type, assign items=(). Use unset items to remove the variable. All index operands here are fixed or generated by the array itself.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Append after a gap
items=([0]=a [4]=b)items+=(c 'd e')for i in "${!items[@]}"; do printf '%s:%s\n' "$i" "${items[i]}"; doneExpected stdout:
0:a4:b5:c6:d eAppending starts at index 5, not at count 2.
Remove without renumbering
items=(a b c)unset 'items[1]'items+=(d)printf '%s\n' "${!items[@]}"Expected stdout:
023Index 1 remains missing.
Slice sparse array
items=([0]=a [3]=b [8]=c [9]=d)printf '%s\n' "${items[@]:2:2}"Expected stdout:
bcThe first assigned index at or beyond 2 is 3; length 2 selects b and c.
Common mistakes
Unsetting an element does not compact the array. Do not assume the next appended index equals the number of elements. Quote an unset subscript even if it looks harmless: square brackets also have glob meanings.
Practice
Create indices 0, 2 and 5, remove index 2, append a value, then print all remaining indices. Slice from offset 1 with length 2 and compare selected values with actual indices.
Next: Associative arrays