Check whether a file/folder exists, with cmd command-line (NOT batch script)
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence
--
Chapters
00:00 Check Whether A File/Folder Exists, With Cmd Command-Line (Not Batch Script)
00:23 Answer 1 Score 13
00:30 Answer 2 Score 4
00:40 Answer 3 Score 7
01:04 Accepted Answer Score 24
02:11 Thank you
--
Full question
https://superuser.com/questions/541534/c...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#windows #commandline
#avk47
ACCEPTED ANSWER
Score 24
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 ( https://support.microsoft.com/en-us/kb/65994 ) 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.
ANSWER 2
Score 13
You can use a simple
DIR C:\User
ANSWER 3
Score 7
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.
ANSWER 4
Score 4
Just put if
on the front :)
if exist C:\Users echo It exists!