I would like to translate this Linux/Bash script to Windows shell:

if test -d myDirName; then echo "ok"; else mkdir myDirName; fi

It tests if a directory exists, and if it doesn't it creates it.

link|improve this question

40% accept rate
feedback

4 Answers

up vote 4 down vote accepted
@echo off
IF exist myDirName ( echo myDirName exists ) ELSE ( mkdir myDirName && echo myDirName created)
link|improve this answer
5  
This is correct for testing file existence, but how do you know that it's a directory? The simplest answer is if exist mydirname\ and the rest as you say. Alternately, you could actually get a test binary and use it on Windows. – phogg Dec 6 '10 at 16:58
@phogg: In the context of this specific question: if it exists but is a file, you still cannot mkdir it. – grawity Dec 6 '11 at 13:09
@grawity: If it exists but is a file the script will probably fail later when trying to use it as a directory, which probably isn't what you want. – phogg Dec 6 '11 at 13:30
feedback

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)
link|improve this answer
+1 - this works in all Windows and MS-DOS versions, unlike plain if exist dirname which appears to be specific to Windows NT. – grawity Dec 6 '11 at 13:09
feedback

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

link|improve this answer
feedback
exist myDirName/nul

also is true if myDirName is a file, whis is not the searched functionality

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.