Itération 122442
Itération 122442

Reputation: 2962

How to remove the last element of an array in bash?

The syntax to delete an element from an array can be found here: Remove an element from a Bash array

Also, here is how to find the last element of an array: https://unix.stackexchange.com/questions/198787/is-there-a-way-of-reading-the-last-element-of-an-array-with-bash

But how can I mix them (if possible) together to remove the last element of the array ?

I tried this:

TABLE_COLUMNS=${TABLE_COLUMNS[@]/${TABLE_COLUMNS[-1]}}

But it throws:

bad array subscript

Upvotes: 1

Views: 1576

Answers (2)

oguz ismail
oguz ismail

Reputation: 50750

Edit: This is useful for printing elements except the last without altering the array. See chepner's answer for a far more convenient solution to OP.


Substring expansions* could be used on arrays for extracting subarrays, like:

TABLE_COLUMNS=("${TABLE_COLUMNS[@]::${#TABLE_COLUMNS[@]}-1}")

* The syntax is:

${parameter:offset:length}

Both offset and length are arithmetic expressions, an empty offset implies 1. Used on array expansions (i.e. when parameter is an array name subscripted with * or @), the result is at most length elements starting from offset.

Upvotes: 1

chepner
chepner

Reputation: 531035

You can use unset to remove a specific element of an array given its position.

$ foo=(1 2 3 4 5)
$ printf "%s\n" "${foo[@]}"
1
2
3
4
5
$ unset 'foo[-1]'
$ printf "%s\n" "${foo[@]}"
1
2
3
4

Upvotes: 3

Related Questions