Linux find and remove empty folders recursively
- User
Linux find and remove empty folders recursively
- Assistant
To find and remove empty directories recursively in Linux, you can use the
findcommand combined with the-type doption to specify directories and the-emptyoption to match empty directories. You can then use the-deleteoption or the-execoption to remove them. Here's how you can do it:Using
-deleteIf you want to remove the empty directories directly, you can use the following command:
bashfind /path/to/directory -type d -empty -deleteUsing
-execAlternatively, you can use
-exec rmdirto remove the empty directories:bashfind /path/to/directory -type d -empty -exec rmdir {} \;Explanation
/path/to/directory: Replace this with the path of the directory where you want to start the search.-type d: This option tellsfindto look for directories.-empty: This option matches empty directories.-delete: This option removes the matched directories directly.-exec rmdir {}: This option allows executing a command (rmdir) on each found directory. The{}is a placeholder for the found directory, and\;indicates the end of the command.
Important Notes
-
Permissions: Make sure you have the necessary permissions to delete the directories you are targeting.
-
Be Careful: This command will permanently delete empty directories without any confirmation. Double-check the target directory to avoid losing important data.
-
Testing: If you want to test the command without actually deleting anything, you can first run:
bashfind /path/to/directory -type d -emptyThis will list all the empty directories found, allowing you to review them before deletion.
Examples
-
To find and delete empty directories within
/home/user/mydir, you would run:bash
- User
find /path/to/directory -type d -empty -delete
print deleted folders?
- Assistant
If you want to print the names of the empty directories that were deleted while using the
findcommand, you can modify the command slightly to include a feedback mechanism, typically using-execwithechoor employing a temporary action likermdirwhich can also print its argument.Here's one way to do it using
-exec:bashfind /path/to/directory -type d -empty -exec sh -c 'echo "Deleting: $1" && rmdir "$1"' _ {} \;Breakdown of the Command: