One of the fundamental elements of programming is the ability to make comparisons: you test for certain conditions to be able to make decisions. You can use the test command to evaluate many items, such as variables, strings, and numbers. I keep the information in this appendix close at hand since I haven't memorized all of the parameters. I often use these switches for checking files and strings, and this is a simple quick reference for easy lookup. Note that in Table A-1 the "test" column refers to the system command test such as /usr/bin/test. The "bash" and "ksh" columns refer to the built-in test command for those shells.
Table A-1.Test Switches
Switch
test
bash
ksh
Definition
-a FILE
✓
✓
FILE simply exists.
-b FILE
✓
✓
✓
FILE exists and it is a block special file such as a disk device in /dev.
-c FILE
✓
✓
✓
FILE exists and it is a character special file such as a TTY device in /dev.
-d FILE
✓
✓
✓
FILE exists and it is a standard directory.
-e FILE
✓
✓
✓
FILE simply exists.
-f FILE
✓
✓
✓
FILE exists and it is a standard file such as a flat file.
-g FILE
✓
✓
✓
FILE exists and it is set-group-ID. This is the file permission that changes the user's effective group on execution of the file.
-G FILE
✓
✓
✓
FILE exists and its group ownership is the effective group ID of the user.
-h FILE
✓
✓
✓
FILE exists and it is a symbolic link. This is the same as -L.
-k FILE
✓
✓
✓
FILE exists and it has the sticky bit set. This means that only the owner of the file or the owner of the directory may remove the file.
-l STRING
✓
Length of STRING is compared to a numeric value such as /usr/bin/test -l string -gt 5 && echo.
-L FILE
✓
✓
✓
FILE exists and it is a symbolic link. This is the same as -h.
-n STRING
✓
✓
✓
STRING has nonzero length.
-N FILE
✓
✓
FILE exists and has been modified since it was last read.
-o OPTION
✓
✓
True if shell OPTION is enabled, such as set -x.
-O FILE
✓
✓
✓
FILE exists and its ownership is determined by the effective user ID.
-p FILE
✓
✓
✓
FILE exists and it is a named pipe (or FIFO).
-r FILE
✓
✓
✓
FILE exists and it is readable.
-s FILE
✓
✓
✓
FILE exists and its size is greater than zero bytes.
-S FILE
✓
✓
✓
FILE exists and it is a socket.
-t [FD]
✓
✓
✓
FD (file descriptor) is opened on a terminal. This is stdout by default.