变量作为bash数组索引? [英] Variable as bash array index?

查看:248
本文介绍了变量作为bash数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

Bash似乎很满意将变量作为数组索引:

Bash seems perfectly happy with variables as array indexes:

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

这篇关于变量作为bash数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆