50

I want to remove the last entry in my array, and I want the array to show me that it has 1 less entry when I am using the ${#array[@]}. This is the current line I am using:

unset GreppedURLs[${#GreppedURLs[@]} -1]

Please correct me and show me the right way.

0

6 Answers 6

70

The answer you have is (nearly) correct for non-sparse indexed arrays¹:

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

Bash 4.3 or higher added this new syntax to do the same:

 unset arr[-1]

(Note the single quotes: they prevent pathname expansion).

Demo:

arr=( a b c )
echo ${#arr[@]}

3

for a in "${arr[@]}"; do echo "$a"; done
a
b
c
unset 'arr[${#arr[@]}-1]'
for a in "${arr[@]}"; do echo "$a"; done
a
b

Punchline

echo ${#arr[@]}
2

(GNU bash, version 4.2.8(1)-release (x86_64-pc-linux-gnu))


¹ @Wil provided an excellent answer that works for all kinds of arrays

8
  • Works in GNU bash, version 3.1.0(3)-release (sparc-sun-solaris2.9)
    – 0zkr PM
    Aug 24, 2014 at 23:55
  • @Wil I'd disagree with the repeated "wrong" and "fundamentally wrong" etc. Your answer is solid, and you get a +1 for it. This answer is not "wrong", it's less generic. I'd say nothing in the original question suggested associative arrays. Not to mention that when the question was posed Bash 4 was very much a rarity. I'd gladly hand your answer the Accept if I could, because your answer is way more up-to-date. I'd appreciate if you reconsidered all the unnecessary competitive rhetorics though.
    – sehe
    Dec 26, 2016 at 14:00
  • @sehe The data set for the original question isn't provided, that's why I said your answer is wrong - because it makes blind assumptions about the data set... if you want to call my comments "competitive rhetorics", well, lol... you're entitled to look like you do speaking like that.
    – Wil
    Feb 22, 2017 at 19:12
  • 1
    @GézaTörök "Of course" that feature was copied from zsh. It's nice but realize that was added in bash 4.3 (several years after this answer was written). Not every system has a recent bash. E.g. Ubuntu LTS barely has it (4.4). Updated answer text
    – sehe
    May 25, 2020 at 14:12
  • 1
    I would very much like to emphasize the importance of the answer's note: use the variable in quotes to avoid pathname expansion! And to further clarify, the brackets [] are special glob characters (depending of course to your bash glob options, e.g. in a script vs in interactive mode).
    – J. Doe
    Dec 21, 2022 at 10:00
16

You must remove the blank before -1.

0
13

If you'd like an answer which won't eat your kittens, try this:

array=([1]=1 {2..5} [10]=6);
# declare -a array='([1]="1" [2]="2" [3]="3" [4]="4" [5]="5" [10]="6}")'
index=("${!array[@]}");
# declare -a index='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5" [5]="10")'
unset 'array[${index[@]: -1}]';
# declare -a array='([1]="1" [2]="2" [3]="3" [4]="4" [5]="5")'

And there you have it - removing the last element. Now I'll present a much easier answer which probably meets your needs but has a caveat:

array=([1]=1 {2..5} [10]=6);
# declare -a array='([1]="1" [2]="2" [3]="3" [4]="4" [5]="5" [10]="6}")'
array=("${array[@]::${#array[@]}-1}");
# declare -a array='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5")'

This version takes a shortcut. It re-indexes the array and drops the last element. Unfortunately you can also see that the index has not been maintained. The values and their order has been. If you don't care about the index then this is probably the answer you wanted.

Both of the above answers will also work on bash 4 Associative Arrays.

--

The chosen answer is not safe. Here's an example:

array=([1]=1 {2..5} [10]=6);
# declare -a array='([1]="1" [2]="2" [3]="3" [4]="4" [5]="5" [10]="6")'
unset 'arr[${#arr[@]}-1]';
# declare -a array='([1]="1" [2]="2" [3]="3" [4]="4" [10]="6")'

Okay so as you can see it is unsetting the element with index 5 because it incorrectly calculated the index of the last element of the array. It failed because it operated on an assumption that all arrays are zero-based, and not sparse. This answer will fail on arrays starting with anything other than zero, arrays which are sparse, and obviously must fail for an associative array with 'fubar' for the last element.

7
  • 2
    The standard way in Bash≥4 is to just use unset 'arr[-1]'. By the way, your answer is also wrong: you're missing quotes in your unset statements, so your command is subject to pathname expansion. Dec 26, 2016 at 11:23
  • @gniourf_gniourf Does that DoTheRightThing for associative arrays? That would be the slam-down answer
    – sehe
    Dec 26, 2016 at 14:04
  • 2
    @sehe: of course it doesn't work as expected for associative arrays (it will unset the field with key -1). But that's not really an issue: it doesn't really make sense (read: it's not useful) to remove the “last” element of an associative array; what is the “last” element in the case of an associative array? Dec 26, 2016 at 14:06
  • @gniourf_gniourf that's actually a nice point; Indeed bash's associative arrays are unordered. Of course the unspecified order is deterministic - so you /could/ show the list to a user and claim it's useful to have the user "delete the last entry shown". But that's pretty contrived. Thanks for making me think it through.
    – sehe
    Dec 26, 2016 at 14:41
  • @gniourf_gniourf TY for the pointer re: quoting the unset argument. To answer your question about the usefulness of removing the last element of an assoc array - what if you want to pop key/value pairs off a list? You're right about the order not being maintained but that doesn't stop it from being useful.
    – Wil
    Feb 19, 2017 at 6:29
9

For any indexed array (sparse or not), since bash 4.3+ (and ksh93+), this is the simplest of solutions:

unset 'array[-1]'

The quotes are needed to avoid shell expansion in bash if the -1 is an arithmetic expression or a variable. This also works correctly:

a=3; unset 'arr[ a - 4 * 1 ]'

But will not work if unquoted ('') as the * will be expanded to the list of files in the present working directory ($pwd).

For older bash versions: this works since bash 3.0 for non-sparse arrays:

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

Example:

$ arr=( {a..i} ); declare -p arr  
declare -a arr=([0]="a" [1]="b" [2]="c" [3]="d" [4]="e" [5]="f" [6]="g" [7]="h")
$ unset 'arr[ ${#arr[@]}-1 ]'; declare -p arr
declare -a arr=([0]="a" [1]="b" [2]="c" [3]="d" [4]="e" [5]="f" [6]="g")

This will not work for sparse arrays (with some holes):

$ arr=( {a..g} [9]=i ); declare -p arr
declare -a arr=([0]="a" [1]="b" [2]="c" [3]="d" [4]="e" [5]="f" [6]="g" [9]="i")
$ unset 'arr[ ${#arr[@]}-1 ]'; declare -p arr
declare -a arr=([0]="a" [1]="b" [2]="c" [3]="d" [4]="e" [5]="f" [6]="g" [9]="i")

This happens because the count of elements (${#arr[@]}) is 8 and 8-1 is 7.
So, the command will unset arr[7], which doesn't exist. Nothing is done.

A solution, that also work for Associative arrays (in whatever it could mean "the last element" in an unsorted list) is to generate a new array of indexes.
Then use the last index to unset that element.

Assuming arr is already defined (for bash 3.0+):

$ index=( "${!arr[@]}" )          # makes index non-sparse.
$ unset 'arr[${index[@]}-1]'      # unset the last index.
$ declare -p arr
declare -a arr=([0]="a" [1]="b" [2]="c" [3]="d" [4]="e" [5]="f" [6]="g")

A slightly more portable (works in ksh93), that looks ugly, solution is:

$ arr=( {a..e} [9]=i )
$ index=( "${!arr[@]}" )
$ unset "arr[  ${index[${#index[@]}-1]}  ]"   # Yes, double quotes.
$ declare -p arr
declare -a arr=([0]="a" [1]="b" [2]="c" [3]="d" [4]="e")   

Or (again, double quotes for ksh):

$ unset "arr[${index[@]: -1}]"

If you want to avoid the space and the negative number, make it a variable:

$ a="-1"; unset "arr[${index[@]:a}]"
2
  • I like the terseness of unset 'array[-1]', but sadly it is not a valid command in bash v4, which is the most recent version available for my OS. I'll keep it in mind for the future, though. Mar 9, 2020 at 18:34
  • @CameronHudson Then use unset 'array[${index[@]}-1]' since bash 3.0 (which is listed inside this answer).
    – user8017719
    Mar 11, 2020 at 15:57
1

The following works fine for Mac/bash@3.x and Linux (ubuntu/bash@4.x)

unset arr[$[${#arr[@]}-1]] # non-sparse array only

in more details:

len=${#arr[@]}
idx=$[$len-1]    # <=> $(($len-1))
unset arr[$idx]
2
  • The $[ ] syntax is deprecated. Jan 21, 2021 at 18:31
  • working case for GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin21) Mar 23, 2022 at 9:08
1

In your function, you could add the following:

target="${@:$(($#)):1}"
set -- "${@:1:$(($#-1))}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.