Search This Blog

Thursday, April 23, 2009

file test operators in bash

Often while writing shell scripts, various tests need to be performed on files. For example, we need to check if a file exists before copying it somewhere. We need to check the existence of a directory before writing files into it.

Bash comes with the following list of operators to perform these tests.
Operator    Tests Whether
-e File exists
-f File is a regular file
-d File is a directory
-h File is a symbolic link
-L File is a symbolic link
-b File is a block device
-c File is a character device
-p File is a pipe
-S File is a socket
-t File is associated with a terminal

-N File was modified since last read
-O You own the file
-G Group id of the file is same as yours

-s File is not zero size

-r File has read permission
-w File has write permission
-x File has execute permission

-g sgid flag set
-u suid flag set
-k "sticky bit" set

F1 -nt F2 File F1 is newer than F2 *
F1 -ot F2 File F1 is older than F2 *
F1 -ef F2 Files F1 and F2 are hard links to the same file *

! NOT (inverts the sense of above tests)

* signifies a binary operator (requires two operands).

Reference :- Appendix B of "Advanced Bash-Scripting guide" by Mendel Cooper, Version 6.5. Debian users can get this document by installing the abs-guide package.
sudo apt-get install abs-guide

The necessary files can be found in /usr/share/doc/abs-guide . However, the abs-guide package contains only the html version of the document. A pdf version can be downloaded from .