我想删除数组中的最后一个条目,并且我希望数组在我使用 ${#array[@]}
时显示它少了 1 个条目。这是我正在使用的当前行:
unset GreppedURLs[${#GreppedURLs[@]} -1]
请指正并告诉我正确的方法。
最佳答案
您的答案(几乎)正确 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]
(注意单引号:它们防止路径名扩展)。
演示:
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)-release (x86_64-pc-linux-gnu))
¹ @Wil 提供了 excellent answer适用于各种阵列
关于arrays - 从数组中删除最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8247433/