Empty and unset variables in bash
In bash, empty value and not defined value are different. This post will show how to recognize them correctly.
Use Conditional Expressions
Conditional Expressions official reference
[[ $var ]]
returnstrue
if and only ifvar
has non-zero length.-
[[ -z string]]
returnstrue
if and only ifstring
has zero-length. Note:-z
operator evaluates the followed expression, thus, empty and unset values are treated the same -n
is reversed of-z
, i.e.! -z
.[[ -v varname]]
returns true ifvarname
is set regardless of its value length zeroness. Note: this operator takes a variable name, not value.-R
is reversed of-v
, i.e.! -v
.
All these conditional expressions can be preceded with !
for negation.
Use Parameter Expansion
Parameter Expansion official reference
${var:-word}
: ifvar
is unset or null,word
is used, otherwise, usevar
.${var-word}
: ifvar
is unset,word
is used, otherwise, usevar
.${var:+word}
: ifvar
is unset or null, usevar
(i.e. nothing). Otherwise, useword
.${var+word}
: ifvar
is unset, usevar
(i.e. nothing). Otherwise, useword
.