How to check if a file exists in a directory?

I want to perform SQL *Loader operation only if a file named "load.txt" exists in a directory "/home/loc/etc". Please help how to check this with a if condition.

if [ ! -f /home/loc/etc/load.txt ]
then
  echo "File does not exist. Exiting..."
  exit 1
fi

this may help

--ahamed

I have the below one, suggest if this is fine

if [ -s /home/loc/etc/loader.txt ]
then
   echo "File is available"
else
      echo "File is not available"
fi

You are good to go!

--ahamed

Thank you :slight_smile:

@vel4ever , -f will check for the file existence but -s will check for file existence along with file size greater than 0 (zero)..

If you are checking for the existence of a file which is zero sized , then -s option would fail .. Below is the demo ..

$ touch loader.txt
$ ls -ltr loader.txt
-rw-rw-rw-   1 user   gid         0 Jan  9 06:36 loader.txt
$ [ -s loader.txt ] && echo "File there" || echo "File Not there"
File Not there
$ [ -f loader.txt ] && echo "File there" || echo "File Not there"
File there
$
1 Like

Jayan,

Thanks for your nice explanation. -s will suit my requirement well. As i need to load the file only if some data present in the text file.

Please suggest me a source where i can get know about shell scripting. I would love to learn them

This would help you .. http://www.unix.com/answers-frequently-asked-questions/13774-unix-tutorials-programming-tutorials-shell-scripting-tutorials.html

Thanks a lot.