Hat*_*kNZ 8 arrays bash printf
这是我的阵列:
$ ARRAY=(one two three)
Run Code Online (Sandbox Code Playgroud)
如何打印数组,以便输出如下:index i, element[i]使用我在下面使用的printfor for循环
1,one
2,two
3,three
Run Code Online (Sandbox Code Playgroud)
一些注意事项供我参考
1种打印阵列的方法:
$ printf "%s\n" "${ARRAY[*]}"
one two three
Run Code Online (Sandbox Code Playgroud)
2种打印阵列的方法
$ printf "%s\n" "${ARRAY[@]}"
one
two
three
Run Code Online (Sandbox Code Playgroud)
3种打印阵列的方法
$ for elem in "${ARRAY[@]}"; do echo "$elem"; done
one
two
three
Run Code Online (Sandbox Code Playgroud)
4种打印阵列的方法
$ for elem in "${ARRAY[*]}"; do echo "$elem"; done
one two three
Run Code Online (Sandbox Code Playgroud)
一种看待阵列的方式
$ declare -p ARRAY
declare -a ARRAY='([0]="one" [1]="two" [2]="three")'
Run Code Online (Sandbox Code Playgroud)
xxf*_*xxx 21
你可以遍历数组的索引,即从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
Run Code Online (Sandbox Code Playgroud)
产量
1,one
2,two
3,three
Run Code Online (Sandbox Code Playgroud)
Leg*_*egZ 10
最简单的迭代方法似乎是:
#!/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
Run Code Online (Sandbox Code Playgroud)