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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38602587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:22:26  来源:igfitidea点击:

bash + for loop + output index number and element

arraysbashprintf

提问by HattrickNZ

This is my array:

这是我的数组:

$ ARRAY=(one two three)

How do I print the array so I have the output like: index i, element[i]using the printfor forloop I use below

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

1,one
2,two
3,three

Some notes for my reference

一些笔记供我参考

1 way to print the array:

1种打印数组的方法:

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

2 way to print the array

2 打印数组的方法

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

3 way to print the array

打印数组的3种方式

$ for elem in "${ARRAY[@]}"; do  echo "$elem"; done
one
two
three

4 way to print the array

4种方式打印数组

$ for elem in "${ARRAY[*]}"; do  echo "$elem"; done
one two three

A nothe way to look at the array

查看数组的另一种方式

$ declare -p ARRAY
declare -a ARRAY='([0]="one" [1]="two" [2]="three")'

回答by xxfelixxx

You can iterate over the indices of the array, i.e. from 0to ${#array[@]} - 1.

您可以遍历数组的索引,即 from 0to ${#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

回答by LegZ

The simplest way to iterate seems to be:

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

#!/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