击:使用一个变量作为关联数组名 [英] Bash : Use a variable as an associative array name

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

问题描述

我正在写一个Bash脚本,从我们的主要网站,多个机构简化文件副本。
在此脚本中,我试图用一个变量作为关联数组的名字,但我optain错误,这里是code:

I'm writing a Bash script to simplify file copies from our main site to multiple agencies. In this script, I'm trying to use a variable as an associative array name but I optain an error, here is the code :

#!/bin/bash

declare -A GROUP1
declare -A GROUP2
declare -A GROUP3
declare -A ARRAY

GROUP1["SITE1"]="x.x.x.x"
GROUP1["SITE2"]="y.y.y.y"
GROUP1["SITE3"]="z.z.z.z"

GROUP2["SITE1"]="1.1.1.1"
GROUP2["SITE2"]="2.2.2.2"
GROUP2["SITE3"]="3.3.3.3"

GROUP2["SITE1"]="a.a.a.a"
GROUP2["SITE2"]="b.b.b.b"
GROUP2["SITE3"]="c.c.c.c"

read -p "Choose a group of sites : " group

case $group in
    1 ) DEST="GROUP1" ;;
    2 ) DEST="GROUP2" ;;
    3 ) DEST="GROUP3" ;;
esac

eval "ARRAY=(\${$DEST[@]})"

for elem in "${!ARRAY[@]}"
do
   echo $elem
   echo ${ARRAY[$elem]}
done

以下是错误:

./test: line28: TAB : 3.3.3.3 : must use subscript when assigning associative array
./test: line28: TAB : 2.2.2.2 : must use subscript when assigning associative array
./test: line28: TAB : 1.1.1.1 : must use subscript when assigning associative array

正是我试图做可能吗?
先谢谢了。

Is what I am trying to do possible ? Thanks in advance.

推荐答案

这是可能的,但除非你有这并不容易庆典V4.3 。 4.3,您可以使用nameref

It's possible but it's not easy unless you have bash v4.3. With 4.3, you can use a "nameref":

declare -A GROUP1
declare -A GROUP2
declare -A GROUP3

GROUP1["SITE1"]="x.x.x.x"
#...

# Yuk. Use command-line options, not stdin
read -p "Choose a group of sites : " group

for g in GROUP1 GROUP2 GROUP3; do if [[ $group == $g ]]; then

  # Here's the nameref: After this executes, ARRAY is an alias for
  # the indicated variable.
  declare -n ARRAY=$group
  break

fi

### This is documented but might not work depending on bash version
### Instead you could test for existence of a known key:
###    if [[ ! -v ${ARRAY[SITE1]} ]]; then
if [[ ! -R ARRAY ]]; then
 echo "No such group" >> /dev/stderr; exit 1
fi

OK,你可能还没有bash的4.3,但在今后的上方将是有用的人。因此,没有它,你可以按照就像一个你提出,这是指定的关联数组复制的策略。这不是太糟糕,如果阵列并不大。要做到这一点,使用上述但更换nameref线(声明-n ARRAY = $组)与以下内容:

defn=$(declare -p $group)
eval "${defn/$group/ARRAY}"
unset defn

在这种情况下,你必须用成功的替代测试。

In this case, you'll have the use the alternative test for success.

注意:这真的不是使用所有盖帽为庆典变量名是个好主意。该公约是系统生成的环境变量和shell变量内置使用全部大写。用户变量应该是小写为了不与这些predefined变量发生冲突。

Note: It's really not a good idea to use all caps for bash variable names. The convention is that system-generated environment variables and shell builtin variables use all caps. User variables should be lower-cased in order to not collide with these predefined variables.

这篇关于击:使用一个变量作为关联数组名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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