Sometimes, we need to delete or copy files to a different folder. To do it, you need to check whether a file exists or not.

DOS provides conditional statements (if else), allowing you to execute commands based on conditional values.

The exist command is used to check if a file or directory exists in a given directory. For example, the exist file command checks if a file exists in the current directory.

The exist command always returns true or false in a conditional context. True means it executes the command inside an if block, while false means it executes the command inside an else block.

The exist command takes a single file name, directory, or an absolute path of a file or directory.

You can also use not exist to check if a file does not exist in the given directory.

if exist test.bat (
    echo File exists
) else (
    echo File does not exists
)

To check if a given file does not exist:

if not exist c:\test.bat (
    echo File does not exists
) else (
    echo File exists

)

One important point is that exist only works in the context of conditional statements such as if and else.

If you try to execute the command exist c:\test.bat, it will not work, and prints nothing.

exist c:\test.bat

Conclusion

The if else syntax allows you to perform conditional actions based on true and false values. The exist command is used to check if any file or directory exists in a given directory.