test
TLDR
Check if a file exists
SYNOPSIS
test EXPRESSION
[ EXPRESSION ]
DESCRIPTION
test evaluates conditional expressions, returning exit status 0 (true) or 1 (false). It is commonly used in shell scripts for decision-making in if statements and loops.
The command can also be invoked as [ with a closing ] required as the last argument. This bracket syntax is more readable in conditionals: if [ -f file ]; then.
Modern shells also provide [[ which offers additional features like pattern matching and safer string handling, but is not POSIX-compliant.
FILE TESTS
-e FILE
True if file exists.-f FILE
True if file exists and is a regular file.-d FILE
True if file exists and is a directory.-r FILE
True if file is readable.-w FILE
True if file is writable.-x FILE
True if file is executable.-s FILE
True if file exists and has size greater than zero.-L FILE
True if file is a symbolic link.
STRING TESTS
-n STRING
True if string length is non-zero.-z STRING
True if string length is zero.STRING1 = STRING2
True if strings are equal.STRING1 != STRING2
True if strings are not equal.
INTEGER COMPARISONS
INT1 -eq INT2
Equal.INT1 -ne INT2
Not equal.INT1 -lt INT2
Less than.INT1 -le INT2
Less than or equal.INT1 -gt INT2
Greater than.INT1 -ge INT2
Greater than or equal.
OPERATORS
! EXPR
True if expression is false.EXPR1 -a EXPR2
True if both expressions are true (AND).EXPR1 -o EXPR2
True if either expression is true (OR).
CAVEATS
Variables in test expressions should be quoted to handle empty values and spaces correctly. The [ form requires spaces around brackets. String comparison uses = not == for POSIX compliance. Integer comparison operators (-eq, -lt) are different from string operators.
HISTORY
test is one of the original Unix utilities, dating back to Version 7 Unix in 1979. The bracket notation [ was added as an alias for improved readability in shell scripts. Both forms are specified by POSIX and available as shell builtins and standalone commands.


