I have a TARGET variable that can be set to dev, test or prod.
I defined the following lists:
dev=(server1 user1 target1)
test=(server2 user2 target2)
prod=(server3 user3 target3)
Depending on the value of TARGET, I'd like to dynamically associate the variable CONFIG to one of the list.
Let's say TARGET=dev. I then have
eval CONFIG=\$$TARGET # I expect CONFIG to be a list containing (server1 user1 target1)
echo ${CONFIG[*]} # OK, it gives (server1 user1 target1)
echo ${CONFIG[1]} # I would expect to have "server1" but it returns "1", seems like CONFIG is not seen as a list
Any idea ?
eval CONFIG=\$$TARGET
sets CONFIG
to the string $TARGET
. When an array is expanded in a string context, the result is the concatenation of the values in the array, with the first character of IFS
inserted as a separator. Thus after the assignment the value of CONFIG
is the string server1 user1 target1
.
You need to assign to CONFIG
as an array. Since you're working in zsh, you don't need to use eval
to obtain the value of a variable whose name is in a variable. Use the P
parameter expansion flag.
CONFIG=(${(P)TARGET})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With