How to check if a file exists from inside a batch file

WindowsBatch File

Windows Problem Overview


I need to run a utility only if a certain file exists. How do I do this in Windows batch?

Windows Solutions


Solution 1 - Windows

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

Solution 2 - Windows

C:\>help if

Performs conditional processing in batch programs.

> IF [NOT] ERRORLEVEL number command > > IF [NOT] string1==string2 command > > IF [NOT] EXIST filename command

Solution 3 - Windows

Try something like the following example, quoted from the output of IF /? on Windows XP:

IF EXIST filename.txt (
del filename.txt
) ELSE (
echo filename.txt missing.
)

You can also check for a missing file with IF NOT EXIST.

The IF command is quite powerful. The output of IF /? will reward careful reading. For that matter, try the /? option on many of the other built-in commands for lots of hidden gems.  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsabView Question on Stackoverflow
Solution 1 - WindowsChris JView Answer on Stackoverflow
Solution 2 - WindowsSheng Jiang 蒋晟View Answer on Stackoverflow
Solution 3 - WindowsRBerteigView Answer on Stackoverflow