巴什阵列和负下标,是或否? [英] Bash arrays and negative subscripts, yes or no?
问题描述
借助 GNU bash的手动告诉我
如果任何变量分配的索引数组会自动创建
使用语法
An indexed array is created automatically if any variable is assigned to using the syntax
name[subscript]=value
下标作为一个算术前pression处理必须
计算为一个数字。如果标计算为一个数字小于
零,它被用作从一个偏移大于阵列的
最大指数(所以-1 subcript指的最后一个元素
阵列)。
The subscript is treated as an arithmetic expression that must evaluate to a number. If subscript evaluates to a number less than zero, it is used as an offset from one greater than the array’s maximum index (so a subcript of -1 refers to the last element of the array).
所以我想我会给它一个尝试,得到以下结果:
So I figure I will give it a try and get the following result:
$ muh=(1 4 'a' 'bleh' 2)
$ echo $muh
1
$ echo ${muh[*]}
1 4 a bleh 2 # so far so good so now I'll try a negative ...
$ echo ${muh[-1]}
-bash: muh: bad array subscript # didn't go as planned!
难道我做错了什么,或者是网站错误的,或者是GNU的bash,从我的CentOS下运行bash的有什么不同?谢谢!
Did I do something wrong, or is the website wrong, or is gnu bash that different from the bash I am running under CentOS? Thanks!
推荐答案
如果你只是想在最后一个元素
If you just want the last element
$ echo ${muh[*]: -1}
2
如果你想倒数第二个元素
If you want next to last element
$ echo ${muh[*]: -2:1}
bleh
这篇关于巴什阵列和负下标,是或否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!