Skip to content

Instantly share code, notes, and snippets.

@hilbix
Created October 6, 2025 09:51
Show Gist options
  • Save hilbix/ecca5b53ca817f0bd373b0ab679848ef to your computer and use it in GitHub Desktop.
Save hilbix/ecca5b53ca817f0bd373b0ab679848ef to your computer and use it in GitHub Desktop.
@echo off
:: Recursively remove empty directories.
:: Place this into Windows+R shell:sendto as rmdir.bat
:: Then you can use "Send to" "rmdir.bat" to get rid ob all empty directories.
::
:: This is free as in free beer, free speech and free baby
::
:: Why does /s in rmdir cause catastrophic removal of all files instead of removing only empty directories?
::
:: Why is there no way to iterate directories depth-first?
::
:: How do I loop over a loop variable like in: for %%a in (%*) do
:: parser error: for /r %%a %%b in (.) do
:: does not work: for /r !a! %%b in (.) do
::
:: What could be done in 1 line (or some single reasonable command) hence has to look like this:
set FAIL=
:ARGS loop until all args are processed
if //==/%1/ goto END
:LOOP as long as we succeeded in removeing some empty directory
set AGAIN=0
for /r %1 %%x in (.) do (
set LAST="%%~x"
rmdir "%%~x" && set AGAIN=1
)
if %AGAIN% NEQ 0 goto LOOP
:: If the directory still exists, rmdir did not work.
:: Then remember last encountered directory (which must have failed)
if exist %1 set FAIL=%LAST%
:: Process next argument
shift
goto :ARGS
:END
if not //==/%FAIL%/ (
echo FAILED DIRECTORY: %FAIL%
:: pause not needed here, as the newer terminal waits on error codes
exit 1
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment