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=\$$TARGETsetsCONFIGto 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 ofIFSinserted as a separator. Thus after the assignment the value ofCONFIGis the stringserver1 user1 target1.You need to assign to
CONFIGas an array. Since you’re working in zsh, you don’t need to useevalto obtain the value of a variable whose name is in a variable. Use thePparameter expansion flag.