我想从第二个索引开始遍历数组的索引。我该怎么做?
我试过:
myarray=( "test1" "test2" "test3" "test4")
for i in ${!myarray[@]:1}
do
# I only print the indices to simplify the example
echo $i
done
但不起作用。
显然这是可行的:
myarray=( "test1" "test2" "test3" "test4")
myindices=("${!myarray[@]}")
for i in ${myindices[@]:1}
do
echo $i
done
但如果可能,我想将所有内容组合在 for 循环语句中。
最佳答案
使用#
参数长度扩展:
myarray=( "test1" "test2" "test3" "test4")
for (( i=1; i < ${#myarray[@]}; i++ ))
do
# only print the indices to simplify the example
echo $i
done
请注意,!
间接扩展 运算符显然与子字符串扩展 不兼容,因为:
echo "${!myarray[@]:2}"
生成错误代码 1 并输出到 STDERR:
bash: test1 test2 test3 test4: bad substitution
至少对于 bash
的当前版本,v.4.4 和更早版本。不幸的是,man bash
没有充分说明子字符串扩展 不适用于间接扩展。
关于arrays - 在 bash 中循环切片数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637445/