Given I have in a bash script
ev=USER
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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityBy using an indirect expansion (also sometimes called "variable indirection"),
ev=USER
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".
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
.