jewbaby91
jewbaby91

Reputation: 11

Zsh how to access a hard-coded array whose name is passed in as a user argument?

I am attempting to write a small program called systemtheme that exports color hex codes as environment variables to theme other programs. I have hard-coded two themes in the script, onedark and dracula, and I would like to call the script like systemtheme onedark. Here is the working script that does not use user input:

 #! /usr/bin/env zsh
  
 onedark=('#282c34' '#e06c75' '#98c379' ... )
 dracula=('#282a36' '#ff5555' '#50fa7b' ... )

 color_names=('BACKGROUND' 'RED' 'GREEN' 'YELLOW' ... )

 export SYSTEM_THEME="onedark"
 export TRANSPARENT="#00000000"

 for (( i = 1; i <= 17; i++ )); do
     export $color_names[i]=$onedark[$i]
 done

This can be verified because I call those values in other programs, and I can check in the terminal with

> print $RED
#e06c75

I would like to replace the export lines with something like

 export SYSTEM_THEME="$1"
 export TRANSPARENT="#00000000"

 for (( i = 1; i <= 17; i++ )); do
     export $color_names[i]=$1[$i]
 done

but I am running into a lot of trouble. I think there is a way, but I am new to zsh and I'm not too sure the difference between all the ' " $() ${} '${}' ... operations in zsh. Thanks in advance! :)

Upvotes: 1

Views: 57

Answers (1)

chepner
chepner

Reputation: 531325

Indirect parameter expansion is done using the P parameter expansion flag.

export $color_names[i]=${(P)1[$i]}

This allows the value of $1 to be used as the name of the parameter to expand.

Upvotes: 1

Related Questions