What is the standard way, in bash, to check if an environment variable is set up? I'm a little confused between the following options:
! [ -z "${VAR}" ]
[ -n "${VAR}" ]
[ "${VAR}" ]
Or is there a better approach?
-n
checks if a variable is not null.
In bash 4.2 or later you have the -v
operator which checks if a variable is set even if it doesn't have a value, so that might be a scenario you want to cover.
Bash uses the extended test [[
so the "bash" test would be:
[[ -n "$VAR" ]]
However this variable could just be a local variable, if you want to check if it's exported you would need something like:
if env | grep -q '^VAR='; then
env | grep -q '^VAR='
could give false positives if there are environment variables whose values contain \nVAR=
.
Commented
Apr 14 at 13:11
VAR=
) is not the same as having no value (like after unset -v VAR; export VAR
or VAR=()
).
Commented
Apr 14 at 13:13
Try this:
if [[ ! -v VAR ]]; then
echo "unset"
fi
NOTE: Do not expand VAR; use VAR
- not $VAR
VAR
is set to any non-empty value. Regardless of it was received from the shell's environment or marked for exporting to the environment of any programs the shell starts.