Check whether a file/folder exists, with cmd command-line (NOT batch script)

I am on the windows console trying to find out whether a file/folder exists or not.

EXIST could be used in batch, but it is not available on the command-line:

C:\Users\WIN7PR~1>EXIST C:\Users
'EXIST' is not recognized as an internal or external command, operable program or batch file.
0

5 Answers

The solution when the resource is a file it is pretty straight-forward as indicated by others:

C:\> IF EXIST C:\CONFIG.SYS ECHO C:\CONFIG.SYS exists.

Unfortunately, the above does not work for directories. The EXIST function returns the same result for both missing and present folders. Fortunately, there is an obscure workaround:

C:\> IF NOT EXIST C:\FOLDER\NUL ECHO C:\FOLDER missing.
C:\FOLDER missing.
C:\> MD C:\FOLDER
C:\> IF EXIST C:\FOLDER\NUL ECHO C:\FOLDER exists.
C:\FOLDER exists.

It turns out that to support constructs like appending >NUL on command statements, there is a sort of virtual file named "NUL" in every directory. Checking for its existence is equivalent to a check for the directory's existence.

This behavior is documented in a Microsoft knowledge base article ( ) and I have confirmed its behavior on FreeDOS 1.1 and in a Windows 7 command shell.

EXTRA: The KB article indicates this technique can also be used to see if a drive is present. In the case of checking for drive existence, however, caveats exist:

  • An Abort, Retry, Fail? error occurs if the drive is not formatted.

  • Using this technique to check for drive existence depends on device driver implementation and may not always work.

2

You can use a simple

DIR C:\User
0

You can use type command, it will return the contents of a text file without opening it, and for a directory it will return: Access is denied.

If the file or directory is not available you get the message: The system cannot find the file specified.

So for example:

C:\>type c:\temp
Access is denied.
C:\>type c:\example.txt
Some example content in a text file
C:\>type c:\doesnotexist
The system cannot find the file specified.
1

Just put if on the front :)

if exist C:\Users echo It exists!
1

You can use this code:

<pre>
:init
SETLOCAL enabledelayedexpansion
GOTO make_dir
:make_dir
ECHO .
ECHO Checking if exists directory %out_path% ...
CD %out_path%
IF !ERRORLEVEL! GTR 0 ( ECHO Directory doesn't exist, creating... MD %out_path% GOTO make_dir
) ELSE ( ECHO Directory already exists.
)
:GOTO back_it_up
:back_it_up
::Procedure that makes an backup
GOTO done
:done
ECHO Finished
SETLOCAL
EXIT /B
</pre>
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like