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}]"