Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The -z operator is a unary string evaluation operator in Bash that returns true (exit status 0) if the length of its string operand is exactly zero, and false (exit status 1) otherwise. It is executed within the test built-in command or conditional expression constructs ([ ] and [[ ]]) to evaluate the initialization or population state of a variable.

Syntax


# POSIX-compliant test command
test -z "$STRING"


# POSIX-compliant single bracket syntax
[ -z "$STRING" ]


# Bash-specific double bracket keyword syntax
[[ -z $STRING ]]

Evaluation Mechanics

  • Unset Variables: By default, if the operand is an uninitialized (unset) variable, Bash expands it to an empty string prior to evaluation. The -z operator processes this as a zero-length string and evaluates to true (0). However, if the nounset shell option is active (set -u or set -o nounset), referencing an unset variable (e.g., [ -z "$VAR" ]) triggers an “unbound variable” error and halts execution. To safely evaluate a potentially unset variable under set -u, use default parameter expansion (e.g., [ -z "${VAR:-}" ]) to provide an empty fallback without triggering the error.
  • Whitespace: A string containing only whitespace characters (e.g., " ") has a length greater than zero. The -z operator evaluates this as false (1).
  • Complement Operator: The logical inverse of -z is -n, which evaluates to true if the string length is non-zero.

Quoting and Parsing Rules

The parsing behavior of -z depends heavily on the conditional construct used and the application of double quotes around the operand:
  • Single Brackets ([ ]): The operand undergoes word splitting and pathname expansion. If the variable is unquoted and empty, the expression expands to [ -z ]. The test built-in interprets this as a single-argument test evaluating the literal string "-z", which evaluates to true (exit status 0) because the string "-z" has a non-zero length. If the unquoted variable contains spaces, it splits into multiple arguments (e.g., VAR="a b" expanding to [ -z a b ]), which results in a too many arguments error. Double quoting ("$VAR") is strictly required.
  • Double Brackets ([[ ]]): This construct is a shell keyword that suppresses word splitting and pathname expansion. The expression [[ -z $VAR ]] is parsed safely even if $VAR is empty or contains spaces. While quoting is not strictly required here, it is universally recommended for consistency.

Exit Status Codes

ConditionExit StatusResult
length(STRING) == 00True
length(STRING) > 01False
Missing operand in [ ] or test (e.g., [ -z ])0True (POSIX single-argument rule evaluates literal "-z")
Missing operand in [[ ]] (e.g., [[ -z ]])0True (Bash treats -z as a literal string if no operand is provided)
Master Bash with Deep Grasping Methodology!Learn More