这是我的数组:
$ ARRAY=(one two three)
如何打印数组以便得到如下输出:index i, element[i]
使用printf
or for
我在下面使用的循环
1,one
2,two
3,three
一些笔记供我参考
打印数组的1种方法:
$ printf "%s\n" "${ARRAY[*]}"
one two three
2种打印数组的方法
$ printf "%s\n" "${ARRAY[@]}"
one
two
three
打印数组的3种方法
$ for elem in "${ARRAY[@]}"; do echo "$elem"; done
one
two
three
4种打印数组的方法
$ for elem in "${ARRAY[*]}"; do echo "$elem"; done
one two three
查看数组的另一种方式
$ declare -p ARRAY
declare -a ARRAY='([0]="one" [1]="two" [2]="three")'
您可以迭代数组的索引,即来自0
to ${#array[@]} - 1
.
#!/usr/bin/bash
array=(one two three)
# ${#array[@]} is the number of elements in the array
for ((i = 0; i < ${#array[@]}; ++i)); do
# bash arrays are 0-indexed
position=$(( $i + 1 ))
echo "$position,${array[$i]}"
done
Output
1,one
2,two
3,three
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)