Operating System - HP-UX
1833469 Members
2848 Online
110052 Solutions
New Discussion

Re: script question - if file exists

 
SOLVED
Go to solution
Jim Mickens
Frequent Advisor

script question - if file exists

Is there any way in a shell script to check for the existence of a specific file?
9 REPLIES 9
Steven Sim Kok Leong
Honored Contributor
Solution

Re: script question - if file exists

Hi,

Use the -e flag.

#!/sbin/sh
if [ -e $file ]
then
echo $file exists
else
echo $file does not exist
fi

Hope this helps. Regards.

Steven Sim Kok Leong
A. Clay Stephenson
Acclaimed Contributor

Re: script question - if file exists

Sure:

if [ -r ${FNAME} ]
then
echo "File ${FNAME} exists"
else
echo "File ${FNAME} not found"
fi

man test for details.


If it ain't broke, I can fix that.
Bill McNAMARA_1
Honored Contributor

Re: script question - if file exists

in a while:


while [ -f /tmp/file ] ;do
.
.
.
done


Later,
Bill
It works for me (tm)
Jim Mickens
Frequent Advisor

Re: script question - if file exists

Thanks to all. I had a user ask me, and since I'd never tried it before, I had no idea. I'll forward this info to him.
Craig Rants
Honored Contributor

Re: script question - if file exists

If you have the Unix In A Nutshell book, look at the page on test, it will give you about 20 different tests that you can use such as -f for file -x for executable file ...

But -f should work for what you asked.

GL,
C
"In theory, there is no difference between theory and practice. But, in practice, there is. " Jan L.A. van de Snepscheut
Helen French
Honored Contributor

Re: script question - if file exists

Hi,

Check the attachment for all available condtional expressions.

HTH,
Shiju
Life is a promise, fulfill it!
Mark Greene_1
Honored Contributor

Re: script question - if file exists

use the test flags:

-e = exists
-f = plain file
-r = readable file
-d = directory

if [ -r file_name]; then
(do stuff here)
fi

HTH
mark
the future will be a lot like now, only later
Robin Wakefield
Honored Contributor

Re: script question - if file exists

Hi Jim,

The following common flags can be used:

-r file --> if file exists & is readable
-w file --> if file exists & is writable
-x file --> if file exists & is executable
-f file --> if file exists & is not a directory
-d file --> if file exists & is a directory
-s file --> if file exists & size > 0

Rgds, Robin
SHABU KHAN
Trusted Contributor

Re: script question - if file exists

Hi,

man ksh says it all..

-Shabu