63

For example, I have a variable:

env_name="GOPATH"

Now I want to get the environment variable GOPATH as if like this:

echo $GOPATH

How can I get $GOPATH by $env_name?

4

2 Answers 2

68

Different shells have different syntax for achieving this.

In bash, you use variable indirection:

printf '%s\n' "${!env_name}"

In ksh, you use nameref aka typeset -n:

nameref env_name=GOPATH
printf '%s\n' "$env_name"

In zsh, you use P parameter expansion flag:

print -rl -- ${(P)env_name}

In other shell, you must use eval, which put you under many security implications if you're not sure the variable content is safe:

eval "echo \"\$$name_ref\""
1
  • 2
    in bash I used printf '%s\n' "${env_name}" Jun 20, 2018 at 19:42
0

You can avoid eval if you let a shell's prompt expansion handle the indirection:

PS1=\$$env_name sh -si </dev/null 2>&1

This has some advantages - particularly in that the expansion is not followed by command execution. And so the only hazard here is if $env_name contains a command substitution. The variable which it expands to can contain anything which might look like a command substitution without danger because the expansion isn't attempted three times - only twice. In this way validation is fairly easy:

PS1=$"${env_name##*[\'\(]*}" sh -si </dev/null 2>&1

Given a POSIX sh, that should be plenty safe without any risk of arbitrary code execution, while still printing any exported environment variables (of the kind a shell can understand) to standard-out.

1
  • 1
    hmm I can't seem to get this to work, just outputs a blank string ?
    – rudolph9
    Mar 4, 2020 at 0:36

Not the answer you're looking for? Browse other questions tagged .