Overview
Thetest command (also invoked as [) evaluates conditional expressions and returns an exit status of 0 (true) or 1 (false). It’s commonly used in conditional statements and scripts to test files, strings, and numeric values.
Syntax
When using
[, you must close it with ] and include spaces around brackets:File Test Operators
True if FILE exists and is a regular file (not a directory)
True if FILE exists and is a directory
True if FILE exists (file or directory)
String Test Operators
True if STRING is empty (zero length)
True if STRING is not empty (non-zero length)
True if strings are equal
Alternative syntax for string equality (same as
=)True if strings are not equal
Numeric Comparison Operators
True if numbers are equal
True if numbers are not equal
True if NUM1 is less than NUM2
True if NUM1 is less than or equal to NUM2
True if NUM1 is greater than NUM2
True if NUM1 is greater than or equal to NUM2
Examples
File Tests
String Tests
Numeric Comparisons
Practical Use Cases
File Validation
Configuration Validation
Conditional Execution
Script Safety Checks
Version Checking
Input Validation
Combining Tests
Use shell operators to combine multiple tests:Common Patterns
Set Default Value
Create Directory if Missing
Check Multiple Files
Validate Number Range
String Pattern Matching
Exit Status
- True (0)
- False (1)
When the condition is true:
Notes
- Always quote variables to handle empty values correctly:
[ -z "$VAR" ] - Use
-eq,-ne, etc. for numeric comparisons, not=or!= - Use
=or!=for string comparisons, not-eqor-ne - Spaces are required around brackets:
[ -f file ], not[-f file] - The closing
]is required when using[syntax
