test command
The test command, also written with single square brackets, that checks a condition such as a file existing or two values being equal, and exits 0 if it holds.
In more detail
Because [ is an ordinary command, its arguments go through word splitting, so an unquoted empty variable vanishes and [ $x = y ] becomes a syntax error. Quote every variable inside single brackets. It is the portable choice for POSIX sh scripts.
Example
if [ -s empty.txt ]; then echo "has data"; fiRelated terms
- double brackets — Bash's double-bracket test, [[ and ]], a keyword that does not split words or expand globs and adds pattern and regular expression matching.
- file test operators — Test operators that ask about a path: -e exists, -f regular file, -d directory, -s not empty, -r, -w and -x readable, writable and executable.
- integer comparison operators — The test operators that compare whole numbers: -eq equal, -ne not equal, -lt less than, -le at most, -gt greater than and -ge at least.
- word splitting — The step where bash cuts the result of an unquoted expansion into separate words at spaces, tabs and newlines.
Taught in
- The Unquoted Variable: Splitting And Globbing — Bash Scripting & Command Line Automation
- Conditionals: test, Brackets, Double Brackets, case — Bash Scripting & Command Line Automation
- Functions, local And declare — Bash Scripting & Command Line Automation
- Arguments: Dollar One, Dollar At, shift — Bash Scripting & Command Line Automation
- Style That Prevents Bugs — Bash Scripting & Command Line Automation
- POSIX sh Versus Bash — Bash Scripting & Command Line Automation
- Permissions And Ownership — Bash Scripting & Command Line Automation