1

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

Itération 122442
  • 2,644
  • 2
  • 27
  • 73
  • Does this answer your question? [How do I subtract 1 from an array item in BASH?](https://stackoverflow.com/questions/46745252/how-do-i-subtract-1-from-an-array-item-in-bash) – bob dylan Mar 24 '20 at 13:22
  • @bobdylan That question is about subtracting 1 from one element, this question is about removing an element. – Benjamin W. Mar 24 '20 at 13:28
  • https://stackoverflow.com/questions/7174354/bash-array-indexing-minus-the-last-array - wouldn't let me flag more than one question – bob dylan Mar 24 '20 at 13:29
  • Notice that your code works in Bash 4.3 or newer, but it has the (big) flaw of not removing complete elements, but also substring matches. – Benjamin W. Mar 24 '20 at 13:52

2 Answers2

3

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
chepner
  • 497,756
  • 71
  • 530
  • 681
1

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.

oguz ismail
  • 1
  • 16
  • 47
  • 69