Skip to content

Instantly share code, notes, and snippets.

@yogeek
Created January 15, 2018 20:55
Show Gist options
  • Save yogeek/8f1427d1f8b5ca9dbab208d2a3edb5a6 to your computer and use it in GitHub Desktop.
Save yogeek/8f1427d1f8b5ca9dbab208d2a3edb5a6 to your computer and use it in GitHub Desktop.
Bash condition
if [ -z "${VAR}" ]; then
echo "VAR is unset or set to the empty string"
fi
if [ -z "${VAR+set}" ]; then
echo "VAR is unset"
fi
if [ -z "${VAR-unset}" ]; then
echo "VAR is set to the empty string"
fi
if [ -n "${VAR}" ]; then
echo "VAR is set to a non-empty string"
fi
if [ -n "${VAR+set}" ]; then
echo "VAR is set, possibly to the empty string"
fi
if [ -n "${VAR-unset}" ]; then
echo "VAR is either unset or set to a non-empty string"
fi
+-------+-------+-----------+
VAR is: | unset | empty | non-empty |
+-----------------------+-------+-------+-----------+
| [ -z "${VAR}" ] | true | true | false |
| [ -z "${VAR+set}" ] | true | false | false |
| [ -z "${VAR-unset}" ] | false | true | false |
| [ -n "${VAR}" ] | false | false | true |
| [ -n "${VAR+set}" ] | false | true | true |
| [ -n "${VAR-unset}" ] | true | false | true |
+-----------------------+-------+-------+-----------+
The ${VAR+foo} construct expands to the empty string if VAR is unset or to foo if VAR is set to anything
(including the empty string).
The ${VAR-foo} construct expands to the value of VAR if set (including set to the empty string) and foo if unset.
This is useful for providing user-overridable defaults
(e.g., ${COLOR-red} says to use red unless the variable COLOR has been set to something).
The reason why [ x"${VAR}" = x ] is often recommended for testing whether a variable is either unset or set to the empty string
is because some implementations of the [ command (also known as test) are buggy.
If VAR is set to something like -n, then some implementations will do the wrong thing when given [ "${VAR}" = "" ] because the first argument to [ is erroneously interpreted as the -n operator, not a string.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment