Search code examples
windowsbatch-filecmd

How to test if a file is a directory in a batch script?


Is there any way to find out if a file is a directory?

I have the file name in a variable. In Perl I can do this:

if(-d $var) { print "it's a directory\n" }

Solution

  • You can do it like so:

    IF EXIST %VAR%\NUL ECHO It's a directory
    

    However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:

    FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory
    

    The %%~si converts %%i to an 8.3 filename. To see all the other tricks you can perform with FOR variables enter HELP FOR at a command prompt.

    (Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the %% with % in both places.)