bash + for循环+输出索引号和元素

时间:2016-07-27 02:10:49

标签: arrays bash printf

这是我的阵列:

$ ARRAY=(one two three)

如何使用我在下面使用的index i, element[i]printf循环打印数组,以便输出如下:for

1,one
2,two
3,three

供我参考的一些注释

打印数组的一种方法:

$ printf "%s\n" "${ARRAY[*]}"
one two three

打印数组的两种方法

$ 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")'

2 个答案:

答案 0 :(得分:18)

您可以迭代数组的索引,即从0${#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

<强>输出

1,one
2,two
3,three

答案 1 :(得分:9)

最简单的迭代方法似乎是:

#!/usr/bin/bash

array=(one two three)

# ${!array[@]} is the list of all the indexes set in the array
for i in ${!array[@]}; do
  echo "$i, ${array[$i]}"
done