在循环内的bash中创建动态命名的关联数组

时间:2017-07-14 16:41:23

标签: bash associative-array

是否可以创建一个在bash中创建关联数组的循环?
我想沿着这些方向做点什么......

number_of_servers=10;
COUNTER=1

while [  $COUNTER -le ${number_of_servers} ]; do
  declare -A "server_${COUNTER}"
  COUNTER=$((COUNTER+1))
done
非常感谢!

1 个答案:

答案 0 :(得分:0)

您的代码已经有效:

$ for index in 1 2
> do
>     declare -A "server_${index}"
> done
$ declare -p server_1
declare -A server_1
$ declare -p server_2
declare -A server_2

您可以将其简化为@rici pointed out

$ declare -A server_{3..4}
$ declare -p server_4
declare -A server_4

dynamically declare

$ number_of_servers=10
$ declare -A $(printf 'server_%d ' $(seq "$number_of_servers"))
$ declare -p server_10
declare -A server_10