Batch: Testing for Empty Directories

To test whether a directory (or “folder”) is empty, the code

if exist "%dir%\*.*" (
  echo %dir% is non-empty
) else (
  echo %dir% is empty

does not work; it always reports “non-empty”.

The trick

( dir /b /a "%dir%" | findstr . ) > nul && (
  echo %dir% non-empty
) || (
  echo %dir% empty

using conditional execution, however, does work.

Here is an example file using this trick in a separate “function”:

@echo off

goto :main

REM *** === Function "Test" ===================================================

if not "%1" == "" (
  if exist "%1" (
    ( dir /b /a "%1" | findstr . ) > nul && (
      echo %1 non-empty
    ) || (
      echo %1 empty
  ) else (
    echo %1 missing
) else (
  echo error: no parameter
goto :EOF

REM *** === Main ==============================================================


call :test path\to\some\directory

3 Responses to “Batch: Testing for Empty Directories”

  1. Andik Says:

    How to check elegantly with a batch script wether a Folder is absolute empty (no files, no subfolders) and then delete it
    Check this out. To me it’s more elegant because it does not contain quite so complicated commands. It took me a while to come up with that.
    REM ///////////////////////////////////////////////////////////////////////////////
    REM ////////////// ITERATE DIRECTORY FOR EMPTY ////////////////////////////////
    REM ////////////// EMPTY SUBDIRECTORIES ////////////////////////////////
    REM ////////////// AND DELETE THEM ///////////////////////////////////
    REM ///////////////////////////////////////////////////////////////////////////////

    REM Batch procedure that checks a directory structure for empty folders ^(no files, no subdirs^)
    REM And then works on the empty ones, in this case deletes them
    REM Working on the empty ones proved to be more difficult than working on the ones with data.
    REM Explanations
    REM am_DirectoryWhereToDeleteEmptyDirs will be iterated including all its Subdirectories
    REM The first dir command within the for checks whether ^%^%i contains files
    REM If it doesn’t then the second dir command checks whether ^%^%i contains subfolders
    REM Even though, a simple rd command would not delete a directory with subfolders,
    REM So this really is a matter of elegance.
    REM A command after a double pipe will only be executed if the preceding command is considered to have failed
    REM The parameters ^/s ^/b ^/ad only show a directory that has been found, and it is depicted by its full name only.
    REM The good news here is that the dot and double dot for current and parent directory will be skipped.
    REM Find is now told to search for anything it is being passed, but an empty string.
    REM Since I don’t need any output I first limit it to a numeral and then I dump it into nirvana.
    REM The good thing is if nothing has been found then the command is regarded as having failed.
    REM So now I know if it has failed the directory currently being worked on is empty.
    REM And then I happily delete it.
    REM TEEME and Log are special Variables for logging. You don’t have to use them.
    REM I have looked around and all I googled was unsatisfactory.
    REM Either too complicated or too much programming or what have you.
    REM Other advantages of this solution is that is spares you of catching errorlevels and of gotos
    REM So I share this with the www community.
    REM Cheers, Andi.

    for /f “delims=” %%i in (‘dir %am_DirectoryWhereToDeleteEmptyDirs% /s/b/ad ^| sort /r’) do (
    :: Testing whether %%i is empty and can be deleted %TEEME%
    dir /B /A:-D %%i >nul 2>&1 || (
    echo %%i contains no files %TEEME%
    dir %%i /s /b /ad |find /v “” /C >nul 2>&1|| (
    echo Folder %%i contains no Subfolders either and will be deleted now ^.^.^. %TEEME%
    rd “%%i” >>%LOG% 2>>&1
    if {%TRACE%}=={echo} echo. %TEEME%

  2. Howard Bayne Says:

    Every time I am struggling with a command line function for a batch program I stumble across your name eventually. What’s even better is I also find the answer. After struggling with a solution that looks like this:

    for /F %%i in (‘dir /b “%1″‘) do
    echo Folder is NON empty
    goto :EOF

    echo Folder is empty or does not exist

    and getting “The syntax of the command is incorrect” repeatedly. I tried your trick above and got the result I needed on the first try.

    Thanks again Rob!

  3. Stu Says:

    Rob’s solution is helpful to me as it does not require descending into all the possible folders that may exist. That’s a feature we need since, if the given folder is not empty, our script immediately descends into it looking for specific entities so doing that twice is time consuming and wasteful. Thanks! -S

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: