Concept Flow - Array slicing
Define array
Specify slice start and length
Extract slice
Use or display slice
End
Start with an array, choose where to slice and how many elements, then extract and use that slice.
arr=(apple banana cherry date elderberry) start=1 length=3 slice=(${arr[@]:start:length}) echo "${slice[@]}"
| Step | Action | Array State | Slice Indices | Slice Result | Output |
|---|---|---|---|---|---|
| 1 | Define array | [apple, banana, cherry, date, elderberry] | - | - | - |
| 2 | Set slice start=1, length=3 | - | start=1, length=3 | - | - |
| 3 | Extract slice | - | start=1, length=3 | [banana, cherry, date] | - |
| 4 | Print slice | - | - | [banana, cherry, date] | banana cherry date |
| 5 | End | - | - | - | - |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| arr | [apple, banana, cherry, date, elderberry] | [apple, banana, cherry, date, elderberry] | [apple, banana, cherry, date, elderberry] | [apple, banana, cherry, date, elderberry] |
| slice | undefined | undefined | [banana, cherry, date] | [banana, cherry, date] |
| start | undefined | 1 | 1 | 1 |
| length | undefined | 3 | 3 | 3 |
Array slicing in bash:
arr=(a b c d e)
slice=(${arr[@]:start:length})
start = index to begin (0-based)
length = number of elements to extract
slice is a new array with selected elements${array[@]:start:length}?${array[@]:start:length} extracts elements from the array starting at index start and takes length elements.start index with length elements correctly describes this extraction. Other options describe unrelated operations.arr?${array[@]:start:length}. The @ is needed to refer to all elements.${arr[@]:2:3} matches the correct syntax: ${arr[@]:2:3}. ${arr:2:3} misses @, which is required for arrays. Options B and D use invalid syntax.arr=(a b c d e), what is the output of echo ${arr[@]:1:3}?(a b c d e). The slice starts at index 1 and takes 3 elements.arr=(x y z)
echo ${arr:1:2}${arr:1:2} without @. For arrays, @ is needed to slice multiple elements.@, Bash uses the first element x as a scalar string and slices it from index 1 length 2. Since x has length 1, it outputs an empty string.arr=(1 2 3 4 5). You want to extract the last 3 elements using array slicing. Which command will do this correctly?${arr[@]:-3} extracts from 3rd from end to the end (last 3 elements).${arr[@]: -3:3} has space after : causing bad substitution. ${arr[@]:3:3} slices from index 3 length 3 but only 2 elements remain (4 5). ${arr[@]:3} slices from 3 to end (4 5). Only ${arr[@]:-3} gets exactly the last 3: 3 4 5.Pass the test and this pattern moves unknown