Windows bat script: how to judge if a file exists?

15,890

Solution 1

You can use exist:

if exist somefile.dat echo It exists

Depending on the "dialect", you can use else statements. At the lowest level, though, some rather ugly logic like this works:

if exist somefile.dat goto fileexists
echo file does not exist
goto alldone

:fileexists
echo file exists

:alldone

Solution 2

Syntax is as follows:

IF [NOT] EXIST filename command

You can use the [NOT] option to execute code if a file doesn't exist as opposed to if the file does exist, however this can be done as an ELSE staement in a standard IF EXIST statement.

IF EXIST stuff.txt (
  ECHO It exists
) ELSE (
  ECHO It doesn't exist
)
Share:
15,890
Bin Chen
Author by

Bin Chen

Updated on June 28, 2022

Comments