38

This question already has an answer here:

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?

marked as duplicate by muru, Scott, Thomas Dickey, Gilles bash Dec 28 '15 at 23:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

40

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
    in bash I used printf '%s\n' "${env_name}" – Gavin Palmer Jun 20 '18 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.