How do I find out all empty files and directories under Linux / Apple OS X / BSD / Unix like operating systems and delete them in a single pass?
You need to use the combination of find and rm command.
| Tutorial details | |
|---|---|
| Difficulty | Easy (rss) |
| Root privileges | May be required for system files. |
| Requirements | find |
WARNING! These examples may crash your computer if executed. Some background process (daemons) may use empty files as a lock files or as default location to lock (chroot) down daemons. Do not delete those files. Usually, located in /var/, /lib/ and other important locations.Method # 1: Find and delete everything with find command only
The syntax is as follows to find and delete all empty directories:
find /path/to/dir -empty -type d -delete
Find and delete all empty files:
find /path/to/dir -empty -type f -delete
Where,
- -empty : Only find empty files and make sure it is a regular file or a directory.
- -type d : Only match directories.
- -type f : Only match files.
- -delete : Delete files. Always put -delete option at the end of find command as find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the starting points you specified.
Method # 2: Find and delete everything using xargs and rm/rmdir command
The syntax is as follows to find and delete all empty directories:
## secure and fast version ### find /path/to/dir/ -type d -empty -print0 | xargs -0 -I {} /bin/rmdir "{}"
OR
## secure but may be slow due to -exec ##
find /path/to/dir -type d -empty -print0 -exec rmdir -v "{}" \;
The syntax is as follows to delete all empty files:
## secure and fast version ### find /path/to/dir/ -type f -empty -print0 | xargs -0 -I {} /bin/rm "{}"
OR
## secure but may be slow due to -exec ## find . -type f -empty -print0 -exec rm -v "{}" \;
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop













{ 2 comments… read them below or add one }
my pruneEmptyDirs script looks like :
perl -MFile::Find -e”finddepth(sub{rmdir},’.')”
zsh only
To delete all empty directories