Slice an Array

To slice an array in Bash, from specific starting upto specific ending index, use the following syntax.

${arrayname[@]:start:end}

where

Variable / Parameter Description
arrayname The array variable, which we would like to slice.
start The starting index of slice.
end The ending index of slice.

Example

In the following script, we take an arrays: arr1 and slice this array from start=1 to end=3.

Example.sh

arr=("apple" "banana" "cherry" "mango" "grape")
sliced=${arr[@]:1:3}
echo $sliced

Output

banana cherry mango

Conclusion

In this Bash Tutorial, we have learnt how to slice an array in Bash shell, with examples.