Undocumented Bash - How to Check if a Shell Variable is Set or Not
狂写 bash 脚本数日,偶有所得。
Usually, we use [ -n "$VAR" ] to check if a shell variable contain non null string. But bash man page does not describe how to check if a shell variable is set or not.
After some search and investigation, I got the following missing bash manual
Parameter Expansion
${parameter-word}
Use Default Values. If parameter is unset, the expansion of word
is substituted. Otherwise, the value of parameter is substituted.
${parameter=word}
Assign Default Values. If parameter is unset, the expansion of
word is assigned to parameter. The value of parameter is then
substituted. Positional parameters and special parameters may not
be assigned to in this way.
${parameter?word}
Display Error if Unset. If parameter is unset, the expansion of
word (or a message to that effect if word is not present) is
written to the standard error and the shell, if it is not
interactive, exits. Otherwise, the value of parameter is
substituted.
${parameter+word}
Use Alternate Value. If parameter is unset, nothing is
substituted, otherwise the expansion of word is substituted.
Some section in bash man page for reference
${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion
of word is substituted. Otherwise, the value of parameter is
substituted.
${parameter:=word}
Assign Default Values. If parameter is unset or null, the
expansion of word is assigned to parameter. The value of
parameter is then substituted. Positional parameters and special
parameters may not be assigned to in this way.
${parameter:?word}
Display Error if Null or Unset. If parameter is null or unset,
the expansion of word (or a message to that effect if word is not
present) is written to the standard error and the shell, if it is
not interactive, exits. Otherwise, the value of parameter is
substituted.
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing is
substituted, otherwise the expansion of word is substituted.
Here are some examples
[ -n "${VAR+x}" ] ## Fails if VAR is unset
[ -n "${VAR:+x}" ] ## Fails if VAR is unset or empty
[ -n "${VAR}" ] ## Fails if VAR is unset or empty
[ -n "${VAR-x}" ] ## Succeeds if VAR is unset
[ -n "${VAR:-x}" ] ## Succeeds if VAR is unset or empty
[ -z "${VAR}" ] ## Succeeds if VAR is unset or empty
0 TrackBacks
Listed below are links to blogs that reference this entry: Undocumented Bash - How to Check if a Shell Variable is Set or Not.
TrackBack URL for this entry: http://www.mamiyami.com/mt/mt-tb.cgi/48

Good tricks! These methods are also applicable for indirect references, for example:
# export NAME=Yan
# export VAR=NAME
# [ -n "${!VAR+x}" ]