Operating System - HP-UX
1820635 Members
1785 Online
109626 Solutions
New Discussion юеВ

How do I check whether a file exists using Shell Script ?

 
SOLVED
Go to solution
Praveen Hari
Advisor

How do I check whether a file exists using Shell Script ?

How do I check whether a file exists in current directory and in a particular directory ?
e.g.
I like to see whether a file called a.txt exists in current directory ?
I like to see whether a file called a.txt exists in ..\temp directory ?

Thanks
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor
Solution

Re: How do I check whether a file exists using Shell Script ?

Hi:

To see if a file called 'a.txt' exists, do:

if [ -f a.txt ]; then
echo "I exist!"
else
echo "I exist not!"
fi

See the man pages for 'test(1}'.

Regards!

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: How do I check whether a file exists using Shell Script ?

#!/usr/bin/sh

FNAME="./a.txt"
if [[ -f "${FNAME}" ]]
then
echo "File ${FNAME} exists"
else
echo "File ${FNAME} not found"
fi

FNAME="../temp/a.txt"

# now same as above

This actually tests to see if the file exists and is a regular file. Man test for details.
If it ain't broke, I can fix that.
Mark Grant
Honored Contributor

Re: How do I check whether a file exists using Shell Script ?

Chek out "test"

Things like

if test -e filename
then

THis will check it exists. You can use [ instead of test so

if [ -e filename ]
then

works or you can just miss out the "if" as in

[ -e filename ] && {
your command go
here
}
Never preceed any demonstration with anything more predictive than "watch this"
Scot Bean
Honored Contributor

Re: How do I check whether a file exists using Shell Script ?

Caution: using [ -e filename ] does not work on standard HPUX.

-e is is only available in newer shell versions