TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
-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
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
-zoperator processes this as a zero-length string and evaluates to true (0). However, if thenounsetshell option is active (set -uorset -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 underset -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-zoperator evaluates this as false (1). - Complement Operator: The logical inverse of
-zis-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 ]. Thetestbuilt-in interprets this as a single-argument test evaluating the literal string"-z", which evaluates to true (exit status0) 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 atoo many argumentserror. 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$VARis empty or contains spaces. While quoting is not strictly required here, it is universally recommended for consistency.
Exit Status Codes
| Condition | Exit Status | Result |
|---|---|---|
length(STRING) == 0 | 0 | True |
length(STRING) > 0 | 1 | False |
Missing operand in [ ] or test (e.g., [ -z ]) | 0 | True (POSIX single-argument rule evaluates literal "-z") |
Missing operand in [[ ]] (e.g., [[ -z ]]) | 0 | True (Bash treats -z as a literal string if no operand is provided) |
Master Bash with Deep Grasping Methodology!Learn More





