Bash: How to Remove Last Element from Array


Often you may want to remove the last element from an array in Bash.

You can use the following syntax to do so:

unset 'my_array[${#my_array[@]}-1]'

This particular example will remove the last element from the array named my_array.

The following example shows how to use this syntax in practice.

Example: How to Remove Last Element from Array in Bash

Suppose we create the following array in Bash named my_array that contains the names of various basketball teams:

my_array=(Mavs Hawks Nets Spurs Warriors Celtics Kings)

We can use the following syntax to print each element in the array:

echo "${my_array[@]}"

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

Now suppose that we would like to remove the last element ( “Kings” ) from the array.

We can use the following syntax to do so:

unset 'my_array[${#my_array[@]}-1]'

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

Bash remove last element from array

Notice that when we use the echo statement to view the array once again we can see that the last element has been removed while all other elements have remained.

Note that in this example we used an array with only seven elements but this syntax will work with an array of any size.

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 Find Minimum and Maximum Values in Array
Bash: How to Slice an Array
Bash: How to Append Values to Array

Leave a Reply