This question already has an answer here:

Given I have in a bash script


How can I get the environment variable value for $USER using ev?

Tried naively doing:

echo ${"$"$ev}

which results in bad substitution.

I'd expect to get back whatever the value of $USER is.

marked as duplicate by terdon bash Mar 1 at 18:22

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.


By using an indirect expansion (also sometimes called "variable indirection"),

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

This is described in the bash (5.0) manual, in the section titled "Parameter Expansion".

Or, by making ev a name reference (requires bash 4.3+),

declare -n ev=USER
printf '%s\n' "$ev"

This is described in the bash (5.0) manual, just before the section called "Positional Parameters".

  • Perfect thanks ... env_val="${!ev}" – PaulB Mar 1 at 10:36

If it's only about environment variables, as opposed to shell variables, then on most systems, you can use:

printenv -- "$ev"

For shell variables, with any Bourne-like shell, you can do:

eval 'printf "%s\n" "${'"$ev"}'}"'

Or with zsh:

printf '%s\n' "${(P)ev}"

Or with bash:

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

All 3 are arbitrary command injection vulnerabilities if the content of $ev is not under your control.


You can also evaluate the command after the vale for $ev has been substituted:

eval echo "$"$ev

The part "$"$ev resolves to $USER so eval executes echo $USER.

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