6

I want to know if a particular environment variable is set or not, from the command line. I need to distinguish between it being set to a blank string (or just whitespace) and not set at all, so I'd like to get a definitive True/False or Yes/No, not just printing nothing if it's not set.

I know that in a script, I can use -z, but I'm not sure if/how I can do it directly from the command line.

I tried this:

$ echo -z "${MY_URDSFDFS}"

But it just prints:

-z
3

2 Answers 2

12

Use the ${VAR+TEXT} form of parameter expansion. ${VAR+1} is empty if VAR is unset and 1 is VAR is set, even if it's empty. (Whereas ${VAR:+1} is empty if VAR is unset or empty, and 1 if VAR is set to a non-empty value.)

if [ -n "${MY_URDSFDFS+1}" ]; then
  echo "\$MY_URDSFDFS is set"
else
  echo "\$MY_URDSFDFS is not set"
fi

This works in any POSIX or Bourne shell, i.e. in all modern and even most ancient dialects of sh.

This does not distinguish between environment variables and shell variables. If you must reject non-exported shell variables, you can do the test in a separate process: sh -c 'test -n "${MY_URDSFDFS+1}"'. This is rarely a concern though.

Please note that this is usually a bad idea, because sometimes it's inconvenient to unset a variable and sometimes it's inconvenient to set it to an empty string. Usually an empty environment variable should be treated identically to an unset one.

1
  • Tested the first code block, possibly a missing double-quote: after the second echo starting the \$MY_URDSFDFS is not set" string? Commented Jun 20, 2021 at 2:12
3

In the zsh shell, to test whether a variable is set, beside the standard [ -n "${var+set}" ], you can also use (( $+var )), where $+var expands to 1 if $var is set and to 0 otherwise.

Note that in zsh, when you do export var while $var was previously unset, unless zsh is running in sh or ksh emulation, a value is automatically assigned (0 for numeric variables, empty list for array/hash variables (not that it makes sense to export those), empty list otherwise), so those tests will return true.

To test that a variable is set and that it is in the environment, you can do

if [[ -$parameters[var]- = *-export-* ]]; then
  echo var is set and exported to the environment
fi

(or ${(t)var} instead of $parameters[var]).

See also this answer to "How do I check if a variable exists in an 'if' statement?" for further considerations on the matter.

You must log in to answer this question.

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