且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从数组中删除最后一个元素

更新时间:2023-08-25 22:21:52

您的答案(几乎)是正确的用于非稀疏索引数组¹:

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

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

Bash 4.3或更高版本添加了此新语法来执行相同的操作:

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

 unset arr[-1]

(请注意单引号:它们会阻止路径名扩展).

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

演示:

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

冲床

echo ${#arr[@]}

2

(GNU bash,版本4.2.8(1)-发行版(x86_64-pc-linux-gnu))

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

¹@Wil提供了一个出色的答案,适用于各种数组

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