How to find and delete directory recursively on Linux or Unix-like system
I type ‘find . -type d -iname foo -delete‘ command to find the foo directories and delete them. However, I am getting an error message that read as find: cannot delete './hourly.4/data/foo': Directory not empty on Linux server. How do delete directories based on find command output on Linux or Unix-like system?
The -delete option remove the DIRECTORY(ies), if they are empty. You need to use the -execoption to delete all directories and its contents. The syntax is as follows.
Find command syntax to delete dirs
Try:
find /dir/to/search/ -type d -name "dirName" -exec rm -rf {} +
OR
find /dir/to/search/ -type d -name "dirName" -exec rm -rf \;
Warning: Be careful with the rm command when using with find. You may end up deleting unwanted data.
Find will execute given command when it finds files or dirs. For example:
find . -type d -name "foo" -exec rm -rf {} +
OR
find . -type d -name "bar" -exec rm -rf "{}" \;
Sample outputs:
removed './daily.0/bar/.cache/motd.legal-displayed' removed directory './daily.0/bar/root/.cache' removed './daily.0/bar/.lesshst' removed './daily.0/bar/.viminfo' removed './daily.0/bar/.vim/.netrwhist' removed directory './daily.0/bar/root/.vim' removed './daily.0/bar/root/.bashrc' removed './daily.0/bar/.ssh/authorized_keys' removed directory './daily.0/bar/root' removed directory './daily.0/bar/var/spool/cron/crontabs'
You can find directories that are at least four levels deep in the working directory /backups/:
find /backups/ -type d -name "bar" -depth +4 -print0 -exec rm -rf {} +
Find and xargs
The syntax is as follows to find and delete directories on Linux/Unix system:
## delete all empty dirs ##
find /path/to/dir/ -type d -empty -print0 | xargs -0 -I {} /bin/rm -rf "{}"
## delete all foo dirs including subdirs in /backups/
find /backups/ -type d -name "foo*" -print0 | xargs -0 -I {} /bin/rm -rf "{}"
The second command is secure and fast version as it deals with weird dir names such as:
- “foo bar”
- “Foo _ *bar”