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" }
This works:
if exist %1\* echo Directory
Works with directory names that contains spaces:
C:\>if exist "c:\Program Files\*" echo Directory
Directory
Note that the quotes are necessary if the directory contains spaces:
C:\>if exist c:\Program Files\* echo Directory
Can also be expressed as:
C:\>SET D="C:\Program Files"
C:\>if exist %D%\* echo Directory
Directory
This is safe to try at home, kids!
Recently failed with different approaches from the above. Quite sure they worked in the past, maybe related to dfs here. Now using the files attributes and cut first char
@echo off
SETLOCAL ENABLEEXTENSIONS
set ATTR=%~a1
set DIRATTR=%ATTR:~0,1%
if /I "%DIRATTR%"=="d" echo %1 is a folder
:EOF
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.)
Further to my previous offering, I find this also works:
if exist %1\ echo Directory
No quotes around %1 are needed because the caller will supply them. This saves one entire keystroke over my answer of a year ago ;-)
Here's a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.
@echo off
if [%1]==[] goto usage
for /f "delims=" %%i in ("%~1") do set MYPATH="%%~fi"
pushd %MYPATH% 2>nul
if errorlevel 1 goto notdir
goto isdir
:notdir
echo not a directory
goto exit
:isdir
popd
echo is a directory
goto exit
:usage
echo Usage: %0 DIRECTORY_TO_TEST
:exit
Sample output with the above saved as "isdir.bat":
C:\>isdir c:\Windows\system32
is a directory
C:\>isdir c:\Windows\system32\wow32.dll
not a directory
C:\>isdir c:\notadir
not a directory
C:\>isdir "C:\Documents and Settings"
is a directory
C:\>isdir \
is a directory
C:\>isdir \\ninja\SharedDocs\cpu-z
is a directory
C:\>isdir \\ninja\SharedDocs\cpu-z\cpuz.ini
not a directory