Check to see if a file exists?

Hi. I'd like to have an IF-Then-Else statement where I can check to see if a file exists? We have the Bourne Shell by default. I'm looking for the syntax to do something like this:

if myfile.txt exists then

...my code

else

...my code

end if

Any help would be greatly appreciated. Thanks.

Have a read of your man page of test.

1 Like
1 Like

Or:

if [ -f myfile.txt ]
then
          # Do something
else
          # Do something else
fi

See the man pages for your Shell for the syntax of "if" and "man test" for detail on the options. There are subtle variations between unix computers. The "-f" option is universal but you won't always find the "-e" option mentioned in post #3.

The OP asked about if a file exists...
However a file may exist, but NOT be a regular file...
So,

if [ -a myfile.txt ]

Should be be considered as an alternative.

EDIT: @methyl, Not trying to teach you, because you could teach me a lot, just trying to point out to the OP a different test construct.

Possibly being a bit too picky here....
Neither the POSIX nor the Linux man pages for test list -a as a valid syntax other than when used as an AND: expression -a expression . I believe that -a is deprecated and that -e is the preferred option to test if a file exists.

There is an interesting disclaimer in the SunOS version of the test manual page. It does list -a and -e, but indicates that neither is available under sh . This implies that the Bourne shell distributed by Sun is a customised version with the test command built-in rather than existing as an external binary. The OP didn't list their O/S, but if they are using some flavour of SunOS, then the -f option might be the best thing available, or they may need several specific tests if indeed they are sussing out non-regular files.