Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

8
  • 10
    Except that it's wrong. You have to check for the NUL device, otherwise it won't work. See my answer three years earlier than this one. Commented Feb 11, 2016 at 21:39
  • 2
    @MartinSchapendonk This works on Windows 7 and Windows Server 2012 as far as I can tell from testing, and I'd be very surprised if it doesn't work at least back to XP and up to Windows 10. Can you provide the conditions when this doesn't work? Commented Mar 10, 2016 at 19:00
  • 19
    @jpmc26 testing for NUL is to make sure you test for a directory. Otherwise the condition might evaluate to true, even it is a regular file. That is the difference. Commented Mar 13, 2016 at 10:24
  • 7
    @MartinSchapendonk Is adding a trailing slash is sufficient for that? That seems to distinguish between files and directories correctly, but there is a weakness in that if the file is not detected, creation of the directory will fail. I suspect this is a problem with testing for NUL, too. Commented Mar 13, 2016 at 19:31
  • 12
    @jpmc26 You are right, a trailing slash does the job and is actually preferable since it works with quotes (thus allowing you to have spaces in the directory path). To distinguish between either file/directory, this will work: if exist "a" if not exist "a\" (echo "it's a file") else (echo "it's a dir"). About your last sentence, I suspect something is wrong with your batch file elsewhere. Commented Dec 12, 2016 at 3:45