从数组中删除最后一个元素 [英] Remove the last element from an array

查看:951
本文介绍了从数组中删除最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除数组中的最后一个条目,并且希望该数组向我显示在使用${#array[@]}时它少了1个条目.这是我正在使用的当前行:

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.

推荐答案

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

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

这篇关于从数组中删除最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆