How to Slice an Array in Bash (With Examples)


Often you may want to slice an array in Bash to extract only specific elements.

You can use the following methods to do so:

Method 1: Extract Specific Element from Array

echo "${my_array[1]}"

This particular example will extract the element in index position 1 of the array named my_array.

Note: The first element in the array has an index value of 0.

Method 2: Extract Specific Range of Elements from Array

echo "${my_array[@]:1:4}"

This particular example will extract elements in index positions 1 through 4 of the array named my_array.

Method 3: Extract All Elements Starting from Specific Index of Array

echo "${my_array[@]:2}"

This particular example will extract all elements in the array starting from index position 2 to the end of the array named my_array.

The following examples show how to use each of these methods in practice with the following array named my_array:

my_array=(Mavs Hawks Nets Spurs Warriors Celtics Kings)

Example 1: Extract Specific Element from Array in Bash

We can use the following syntax to select only the element in index position 1 of the array:

echo "${my_array[1]}"

The following screenshot shows how to use this syntax in practice:

Bash slice specific element in array

Notice that this returns only the element in index position 1 of the array.

Example 2: Extract Specific Range of Elements from Array in Bash

We can use the following syntax to select only the elements in index positions 1 through 4 of the array:

echo "${my_array[@]:1:4}"

The following screenshot shows how to use this syntax in practice:

Bash slice range of elements in array

Notice that this returns only the elements in index positions 1 through 4 of the array.

Example 3: Extract All Elements Starting from Specific Index of Array in Bash

We can use the following syntax to select all of the elements from index position 2 to the end of the array:

echo "${my_array[@]:2}"

The following screenshot shows how to use this syntax in practice:

Bash slice elements from specific index to end of array

Notice that this returns all elements from index position 2 to the end of the array.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Read Lines of File into Array
Bash: How to Read Columns from CSV File into Arrays
Bash: How to Generate Random Number in Range

Leave a Reply