How to get the array name from a variable

女生的网名这么多〃 提交于 2020-01-15 12:22:19

问题


How to get the array name from the below ?

Getting the name of the array from config :

jobcfgUniqName=`echo ${config_data} | awk -F "#" '{print $3}'`

Creating an array of it :

for ((xx = 0; xx <= ${#joblognameSearch[@]}; xx++))
do
    print $joblognameSearch[$xx]
    eval ($jobcfgUniqName)[$xx]=`grep -B 3 -i  error  $joblogPath/$joblognameSearch[$xx]`
    print jobcfgUniqName : ${jobcfgUniqName}
done

This line I tried changing many ways but did not work :

eval ($jobcfgUniqName)[$xx]

回答1:


You can use declare bulletin of BASH to replace your eval by this:

declare arr_"$jobcfgUniqName"[$xx]=`grep -B 3 -i error $joblogPath/$joblognameSearch[$xx]`

Now you will have dynamic array create with prefix arr_ and some variable name $jobcfgUniqName.

TESTING:

# set the array
s='abc'
declare arr_"$s"[0]='foo'
declare arr_"$s"[1]='bar'

# retrieve the values
v1=arr_"$s"[0]
v2=arr_"$s"[1]

echo "${!v1}"
foo
echo "${!v2}"
bar



回答2:


Add echo.

Example:

#!/bin/bash
A="abcd dcba"
B=A
C='eval "echo \$$B"'
eval "$C"

$ bash 1.sh
abcd dcba


来源:https://stackoverflow.com/questions/21620488/how-to-get-the-array-name-from-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!