访问最后但bash的数组元素 [英] access last but element of bash array

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

问题描述

我可以访问数组的所有元素,像这样:

I can access all element of an array like so:

echo ${myarray[@]}

和元素数:

echo ${#myarray[@]}

和我可以做获得的第n个元素:

and I can get the nth element by doing:

echo ${myarray[@]:(-1)}

不过我尝试以下方法来获得第n-1的数组元素:

however I try the following to get the n-1th array element:

echo ${myarray[@]:(-2)}

但我结束了最后两个元素。我怎么只能获得倒数第二个元素?

but I end up with the last two elements. How do I only obtain the last but one element?

推荐答案

您可以添加其他结肠,并指定片的长度:

You can add another colon, and specify the length of your slice:

echo "${myarray[@]: -2: 1}"

例如(虽然我很惭愧地表明这台机器上的bash我的复古版...):

For example (although I'm ashamed to show my vintage version of bash on this machine...):

$ echo "$BASH_VERSION"
3.1.20(4)-release
$ a=( 1 2 3 )
$ echo ${a[@]: -2: 1}
2

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

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