Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh and dynamic variable

Tags:

shell

zsh

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 ?

like image 483
Luc Avatar asked Jan 18 '23 03:01

Luc


1 Answers

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})
like image 159
Gilles 'SO- stop being evil' Avatar answered Feb 01 '23 01:02

Gilles 'SO- stop being evil'