user1601716
user1601716

Reputation: 1993

eval array value bash

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!

Upvotes: 0

Views: 1524

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295472

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.

Upvotes: 1

Related Questions