Empty and unset variables in bash

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 ]] returns true if and only if var has non-zero length.
  • [[ -z string]] returns true if and only if string 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 if varname 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}: if var is unset or null, word is used, otherwise, use var.
  • ${var-word}: if var is unset, word is used, otherwise, use var.
  • ${var:+word}: if var is unset or null, use var (i.e. nothing). Otherwise, use word.
  • ${var+word}: if var is unset, use var (i.e. nothing). Otherwise, use word.
Buy Me A Coffee