[How To] Check for presence of File in Unix

[Unix] Check for presence of File

How do I test existence of a text file in bash running under Unix like operating systems?

The simplest way is to use the special file operators available with Shell and determine the presence of a file. Various other properties of file can also be determined; they are enlisted in this post.

Existence of a file can be determined with the help of -f operator. Following script determines the existence of the file passed as a parameter to the script in the present directory.

# the filename whose existence is to be determined should
# be passed as parameter to this script.
# eg. $ scriptname.sh file_to_be_found.txt


if [ -f $1 ]; then
echo " file present";
else
echo " file not present";
fi


#End of script

Other file test operators as are follows:
       -b FILE              FILE exists and is block special
       -c FILE              FILE exists and is character special
       -d FILE              FILE exists and is a directory
       -e FILE              FILE exists
       -f FILE              FILE exists and is a regular file
       -g FILE              FILE exists and is set-group-ID
       -G FILE              FILE exists and is owned by the effective group ID
       -h FILE              FILE exists and is a symbolic link (same as -L)
       -k FILE              FILE exists and has its sticky bit set
       -L FILE              FILE exists and is a symbolic link (same as -h)
       -O FILE              FILE exists and is owned by the effective user ID
       -p FILE              FILE exists and is a named pipe
       -r FILE              FILE exists and read permission is granted
       -s FILE              FILE exists and has a size greater than zero
       -S FILE              FILE exists and is a socket
       -t FD 

              File descriptor FD is opened on a terminal
       -u FILE              FILE exists and its set-user-ID bit is set
       -w FILE              FILE exists and write permission is granted
       -x FILE              FILE exists and execute (or search) permission is granted


The above list of File operators is taken from Unix man pages.