test Command Cheat Sheet
test checks file types and compares values. It returns a 0 exit status for true and 1 for false.
It is arguably the most used command in shell scripting, often seen as [ ].
Synopsis
test EXPRESSION
[ EXPRESSION ]
File Tests
| Flag |
Description |
-e FILE |
Exists |
-f FILE |
Exists and is a regular file |
-d FILE |
Exists and is a directory |
-s FILE |
Exists and size > 0 |
-r FILE |
Readable |
-w FILE |
Writable |
-x FILE |
Executable |
-L FILE |
Symbolic link |
if [ -d "/etc" ]; then
echo "/etc is a directory"
fi
String Comparators
| Operator |
Description |
-z STRING |
Length is zero (Empty) |
-n STRING |
Length is non-zero (Not empty) |
STR1 = STR2 |
Equal |
STR1 != STR2 |
Not equal |
if [ -z "$VAR" ]; then
echo "Variable matches empty string"
fi
Integer Comparators
| Operator |
Description |
-eq |
Equal |
-ne |
Not Equal |
-gt |
Greater Than |
-ge |
Greater or Equal |
-lt |
Less Than |
-le |
Less or Equal |
if [ "$COUNT" -gt 10 ]; then
echo "Count is greater than 10"
fi
Note: These only work for integers.
Logical Operators
| Operator |
Description |
! EXPR |
NOT |
EXP1 -a EXP2 |
AND (Standard [ ] syntax) |
EXP1 -o EXP2 |
OR (Standard [ ] syntax) |
if [ -f "file.txt" -a -w "file.txt" ]; then
echo "File exists AND is writable"
fi
[ ] vs [[ ]]
test is synonymous with [ ... ].
Bash introduces [[ ... ]], which is safer and more powerful.
[[ ]] supports && and || instead of -a and -o.
[[ ]] supports glob matching (=~).
[[ ]] handles variables with spaces better.
Recommendation: Use [[ ... ]] in Bash scripts, and [ ... ] (the test command) only for POSIX sh compatibility.