I think a example would best explain what I need
_v1="windows"
_v2_windows="/mnt/d"
_v2_osx="/Volumes/d"
echo $_v2_`echo $_v1`
I want to echo the value of _v2_windows
but using _v1
to determine which of the two v2
s to get.
I know can use a case
statement to solve the problem but I'm trying to avoid that.
Best Answer
With
zsh
:${(P)varname}
expands to the value of the variable whose name is stored in$varname
. So if$varname
containsvar
,${(P)varname}
expands to the same thing as$var
.${(e)var}
expands to the content of$var
but also performs parameter expansions, command substitution and arithmetic expansion within. So if$var
contains$othervar
,${(e)var}
expands to the same thing as$othervar
.${(P)${var:-something}}
work${:-content}
is one way to have a parameter expansion expand to arbitrary text (herecontent
)(see the manual for details)
So you could do:
Or:
Or do it in two steps:
Or:
Or you could use the standard POSIX syntax:
Beware that if the value of
$_v1
is not under your control, all those amount to an arbitrary command injection vulnerability, you'd need to sanitize the value first.Also note that
zsh
supports associative arrays (and has long beforebash
), so you can do:Which would be a lot more legible, and wouldn't have any of those security implications.