0

I am trying to substitute both the array name and value using eval and losing my mind with combinations that are not working

 $ eval echo \$${port[$index]}${item[0]}${item[8]}
   some_value

declare -a port=('Ex' 'backup' 'DRAC' 'Service');
declare -a item=('net' 'switch' 'port' 'speed' 'cvsswitch' 'vlan' 'link' 'count' 'list')

       for x in $(eval echo \$${port[$index]}${item[0]}${item[8]}) ; do
           eval ${port[$index]}${item[7]}=$[${port[$index]}${item[7]} +1]                                      # incriment count
           eval echo \$${port[$index]}${item[7]}                                                               # set count
           eval \$"${port[$index]}${item[1]}"[\$${port[$index]}${item[7]}]   <---- not working
       done
fi

I am getting the following output when trying to eval this statement to assign the array[index_value] a value.

$ eval \$${port[$index]}${item[1]}[\$${port[$index]}${item[7]}]=abc123
-bash: [1]: command not found
or
$ eval \$${port[$index]}${item[1]}[\$${port[$index]}${item[7]}]=abc123
-bash: [1]=abc123: command not found

Does anyone have advice on how to get this working?

Thanks!

2
  • 1
    What if we stop talking about eval, and ask clearly about the thing you're trying to accomplish, rather than the tool you want to do it with? Commented Feb 25, 2014 at 23:49
  • For instance, when you say eval \$${port[$index]}${item[1]}[\$${port[$index]}${item[7]}]=abc123 -- what, exactly, do you expect that to actually do? Commented Feb 25, 2014 at 23:51

1 Answer 1

1

You don't need eval, and shouldn't use eval, for assignments of this type.

declare -a port=('Ex' 'backup' 'DRAC' 'Service')
declare -a item=('net' 'switch' 'port' 'speed' 'cvsswitch' 'vlan' 'link' 'count' 'list')

index=3 # for example
array_name=${port[$index]}${item[1]}
array_idx=${port[$index]}${item[7]}

declare -A "$array_name" # since your index is non-numeric
printf -v "${array_name}[${array_idx}]" '%s' abc123

This will set Serviceswitch[Servicecount] to abc123.

Assigning your variable names ahead-of-time is better practice anyhow -- makes it easier to diagnose why something failed when you can look at the pieces that built up to it.

See BashFAQ #6 for an exhaustive treatment of the subject, including portability discussion.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.