How to get the array name from a variable

2019-08-03 16:43发布

问题:

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


标签: shell unix ksh