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.


3 Answers 3


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, 2019 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 .