The Computer Oracle

How to check if a directory exists in Windows?

--------------------------------------------------
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: Over a Mysterious Island

--

Chapters
00:00 How To Check If A Directory Exists In Windows?
00:18 Accepted Answer Score 118
00:55 Answer 2 Score 23
01:15 Answer 3 Score 14
01:43 Answer 4 Score 4
02:13 Thank you

--

Full question
https://superuser.com/questions/219050/h...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#windows7 #commandline #batchfile

#avk47



ACCEPTED ANSWER

Score 118


@echo off
IF exist myDirName ( echo myDirName exists ) ELSE ( mkdir myDirName && echo myDirName created)

Added by Barlop

While the above works for this particular situation, the title says about testing specifically for a directory. Phogg's comment using if exist mydirname\ rather than if exist mydirname is the way. Some answers have used \nul but \nul is problematic in NT. Not including a trailing backslash will test for a file or a directory. So, for a directory, include the trailing backslash.




ANSWER 2

Score 23


Here is what I just found out:

You can test if a nul file exists; if the directory exists it will contain a nul file, if the nul file does not exist then the directory does not exist.

IF exist myDirName/nul ( echo myDirName exists ) ELSE ( mkdir myDirName && echo myDirName created)



ANSWER 3

Score 14


Use a backslash, not forward slash: myDirName\nul not myDirName/nul

md foo 
echo.>bar 
for %I in (foo bar xyz) do @( 
  if exist %I ( 
    if exist %I\nul ( 
      echo -- %I is a directory 
    ) else ( 
      echo -- %I is a file 
    ) 
  ) else ( 
    echo -- %I does not exist 
  ) 
)

-- foo is a directory
-- bar is a file
-- xyz does not exist

edit: this only works if directory name does not contain spaces




ANSWER 4

Score 4


I wondered why joe had a downvote as I was experiencing the same kind of problem on Windows 7, namely that

IF EXIST filename\NUL

was returning TRUE for both files and directories. I found an alternative solution at www.robvanderwoude.com/battech_ifexistfolder.php and came up with a revised version of DVF's FOR loop:

FOR %I in (foo bar xyz) DO @( PUSHD %I && (POPD & echo -- %I is a directory) || ( IF exist %I ( echo -- %I is a file ) ELSE ( echo -- %I does not exist ) ) )