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