test
shell scriptingLinux/Unix
The test command is one of the most frequently used commands in Linux/Unix-like operating systems. test Check file types and compare values
Quick Reference
Command Name:
test
Category:
shell scripting
Platform:
Linux/Unix
Basic Usage:
test [options] [arguments]
Common Use Cases
Syntax
test EXPRESSION [ EXPRESSION ] [ OPTION
Options
Option | Description |
---|---|
File Test Operators | |
-b FILE |
True if FILE exists and is a block special file |
-c FILE |
True if FILE exists and is a character special file |
-d FILE |
True if FILE exists and is a directory |
-e FILE |
True if FILE exists |
-f FILE |
True if FILE exists and is a regular file |
-g FILE |
True if FILE exists and is set-group-ID |
-h FILE |
True if FILE exists and is a symbolic link (same as -L) |
-k FILE |
True if FILE exists and has its sticky bit set |
-L FILE |
True if FILE exists and is a symbolic link |
-p FILE |
True if FILE exists and is a named pipe |
-r FILE |
True if FILE exists and is readable |
-s FILE |
True if FILE exists and has a size greater than zero |
-S FILE |
True if FILE exists and is a socket |
-t FD |
True if file descriptor FD is open and refers to a terminal |
-u FILE |
True if FILE exists and its set-user-ID bit is set |
-w FILE |
True if FILE exists and is writable |
-x FILE |
True if FILE exists and is executable |
-O FILE |
True if FILE exists and is owned by the effective user ID |
-G FILE |
True if FILE exists and is owned by the effective group ID |
-N FILE |
True if FILE exists and has been modified since it was last read |
FILE1 -nt FILE2 |
True if FILE1 is newer than FILE2 (modification date) |
FILE1 -ot FILE2 |
True if FILE1 is older than FILE2 |
FILE1 -ef FILE2 |
True if FILE1 and FILE2 refer to the same device and inode numbers |
String Operators | |
-z STRING |
True if STRING is empty |
-n STRING |
True if STRING is not empty |
STRING1 = STRING2 |
True if the strings are equal |
STRING1 != STRING2 |
True if the strings are not equal |
Numeric Comparison Operators | |
INT1 -eq INT2 |
True if INT1 is equal to INT2 |
INT1 -ne INT2 |
True if INT1 is not equal to INT2 |
INT1 -gt INT2 |
True if INT1 is greater than INT2 |
INT1 -ge INT2 |
True if INT1 is greater than or equal to INT2 |
INT1 -lt INT2 |
True if INT1 is less than INT2 |
INT1 -le INT2 |
True if INT1 is less than or equal to INT2 |
Logical Operators | |
! EXPR |
True if EXPR is false |
EXPR1 -a EXPR2 |
True if both EXPR1 and EXPR2 are true |
EXPR1 -o EXPR2 |
True if either EXPR1 or EXPR2 is true |
Examples
How to Use These Examples
The examples below show common ways to use the test
command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.
# Basic Examples Basic
# Test if a file exists
test -f /etc/passwd && echo "File exists"