Linux 变量作为bash数组索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11856132/
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-08-06 14:02:09  来源:igfitidea点击:

Variable as bash array index?

linuxbash

提问by John Hansen

#!/bin/bash

set -x

array_counter=0
array_value=1

array=(0 0 0)

for number in ${array[@]}
do
    array[$array_counter]="$array_value"
    array_counter=$(($array_counter + 1))
done

When running above script I get the following debug output:

运行上述脚本时,我得到以下调试输出:

+ array_counter=0
+ array_value=1
+ array=(0 0 0)
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=1
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=2
+ for number in '${array[@]}'
+ array[$array_counter]=1
+ array_counter=3

Why does the variable $array_counternot expand when used as index in array[]?

为什么变量$array_counter在用作数组 [] 中的索引时不会扩展?

回答by Bob the Angry Coder

Bash seems perfectly happy with variables as array indexes:

Bash 似乎对变量作为数组索引非常满意:

$ array=(a b c)
$ arrayindex=2
$ echo ${array[$arrayindex]}
c
$ array[$arrayindex]=MONKEY
$ echo ${array[$arrayindex]}
MONKEY

回答by user2038893

Your example actually works.

你的例子确实有效。

echo ${array[@]}

confirms this.

证实了这一点。

You might try more efficient way of incrementing your index:

您可以尝试更有效的增加索引的方法:

((array_counter++))