BASH:如何在循环中创建动态数组名称

时间:2013-05-13 13:41:22

标签: arrays bash dynamic

这是我尝试过的:

n=0
for i in aaa bbb ccc; do
  array${i}[$n]=$(date "+%N")
  ((++n))
done
n=0
for i in aaa bbb ccc; do
  echo ${array${i}[$n]}
  ((++n))
done

如何使动态数组名称有效? 非常感谢!

2 个答案:

答案 0 :(得分:3)

您可以使用间接扩展:

#!/bin/bash

# create the arrays
n=0
for i in aaa bbb ccc; do
    let array$i[$n]=$(date "+%N")
    ((++n))
done

# display what we did
n=0
for i in aaa bbb ccc; do
    var=array$i[$n]
    echo ${!var}
    ((++n))
done

请注意,这只会创建数组变量 arrayaaa [0] arraybbb [1] arrayccc [2] ,并且(正如您所料) arrayaaa [0] arrayaaa [1] arrayaaa [2] arraybbb [0] arraybbb [1] arraybbb [2] arrayccc [0] arrayccc [1] arrayccc [2]

答案 1 :(得分:1)

避开eval:

n=0
for i in aaa bbb ccc; do
  eval "array${i}[$n]=$(date "+%N")"
  ((++n))
done