Operating System - HP-UX
1753643 Members
5108 Online
108798 Solutions
New Discussion юеВ

Re: Command to test if file exists

 
Mike Rightmire
Frequent Advisor

Command to test if file exists

I know this is a really dumb question, but I have completely forgotten the if - then test to determine if a file exists. I know it is simple, but I can't remember it or find it anywhere!

HELP!
Thanks,
Mike
"If we treated each person we met as if they were carrying an unspeakable burden, we might almost treat each other as we should." Dale Carnegie
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor

Re: Command to test if file exists

Hi Mike:

Slipped a groove, huh?

if [ -r myfile -a -f myfile ]
then
echo "myfile is readable and is a reguler file"
fi

Simply man test for details.

If it ain't broke, I can fix that.
Sridhar Bhaskarla
Honored Contributor

Re: Command to test if file exists

Mike,

Simple.

if [ -f /wherever/your_file ]
then
echo "your_file is there"
fi

There are other switches like -x, -r etc., for executable, readable etc.,

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
James R. Ferguson
Acclaimed Contributor

Re: Command to test if file exists

Hi Mike:

I don't think you'v "slipped a goove".

To me the 'test' command isnt't necessarily the obvious place to find what you seek. That aside, take a look at '-r' for testing if a file is (r)eadable and therefore by infererence that it exists. Contrast this with the need to determine that it is a regular file instead of a special file (like a device file, or a socket) [-f]; or that the file has a size greater than zero bytes [-s]; or an important, useful test like [-t] to determine whether or not the file is associated with a terminal (ever so useful with scipts when you want to differentiate between a 'cron' initiated process and one started from a shell's command line!

Take a look at these, and other options, in the 'test' command.

Maybe this thread will help you remember ;-)

Regards!

...JRF...