Array Slicing
In this page:
Basic Slicing with Offset and Length
${arr[@]:offset:length} extracts a sub-list of elements starting at index offset, taking up to length elements from there. This avoids manually looping and building a new array by hand.
Example: Basic Slicing with Offset and Length
#!/bin/bash
letters=(a b c d e f)
slice=("${letters[@]:1:3}")
echo "Slice: ${slice[@]}"
Login to try C/C++/Java/PHP code in the editor
Omitting the Length
Leaving out the length argument, ${arr[@]:offset}, takes every element from offset through the end of the array. This is a convenient way to say 'everything after this point'.
Example: Omitting the Length
#!/bin/bash
numbers=(10 20 30 40 50)
rest=("${numbers[@]:2}")
echo "From index 2 onward: ${rest[@]}"
Login to try C/C++/Java/PHP code in the editor
Negative Offsets Count From the End
A negative offset counts backward from the end of the array, but it must be written with a space (or wrapped in parentheses) before the minus sign, like ${arr[@]: -2}, otherwise Bash parses it as the ${var:-default} expansion instead of a slice.
Warning: ${items[@]:-2} (no space) means something completely different -- it's the default-value expansion, not a slice.
Example: Negative Offsets Count From the End
#!/bin/bash
items=(one two three four five)
last_two=("${items[@]: -2}")
echo "Last two items: ${last_two[@]}"
Login to try C/C++/Java/PHP code in the editor
Slicing Strings the Same Way
The identical :offset:length syntax also works directly on plain string variables, extracting a substring by character position instead of array element position. This consistency makes slicing syntax easy to remember across both arrays and strings.
Example: Slicing Strings the Same Way
#!/bin/bash
text="Hello, World!"
echo "Substring: ${text:7:5}"
Login to try C/C++/Java/PHP code in the editor
- Assuming negative offsets count from the start like a normal index; a negative offset means 'count from the end', and it needs a space or parentheses before the minus sign (
${arr[@]: -1}) so Bash doesn't confuse it with the:-default-value operator. - Miscounting the length argument as an end index rather than a count;
${arr[@]:2:3}takes 3 elements starting at index 2, it does not mean 'up to index 3'. - Forgetting slicing syntax applies to both arrays (
${arr[@]:offset:length}) and strings (${str:offset:length}) with the same rules, but they operate on elements vs. characters respectively.
- Syntax:
${arr[@]:offset:length}-- start at indexoffset, take up tolengthelements. - Omitting
lengthtakes everything fromoffsetto the end of the array. - A negative offset counts from the end of the array, but needs a space before the
-(${arr[@]: -2}) to avoid being parsed as the:-default-value expansion. - The same
:offset:lengthslicing syntax works on plain strings, operating on characters instead of array elements.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: