Slice an Array

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

</>
Copy
${arrayname[@]:start:end}

where

Variable / ParameterDescription
arraynameThe array variable, which we would like to slice.
startThe starting index of slice.
endThe 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

</>
Copy
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.