Many times we need to find and delete empty files or directories in UNIX/Linux. Since there is no single command in Unix/Linux which allows you to remove empty files or empty directories rather we need to rely on find command and xargs command. In this UNIX and linux example we will see How to delete empty files and directories. Before removing empty files and directories we need to find those files and there are lots of option available to search for empty directories like find, grep , awk etc. You just need to know correct option. Like in any other operating system empty files and directories in Unix are those whose size is zero. Empty files doesn't contains any content while empty directories does not contain anything at all e.g files or sub-directories. As discussed in previous post 10 frequently used find command examples we can also use find command to search and delete empty files and directories as it provides searching files based on size as well.
let's first create empty file and directory to demonstrate example of how to delete empty files in Unix. We can use same set of commands which we have used in our example of How to find size of files and directories in Unix.
//This will create empty directory inside current directory
test@localhost:~/unix mkdir empty_dir
//This command will find all empty files and directories in Unix
test@localhost:~/unix find . -empty
./empty.txt
./empty_dir
Searching Empty Files and Directory in Unix/Linux
find -empty option prints both empty files and directories. If you just want to print files than use -type f option and -type d for listing empty directories. its quite flexible. You can also use grep command along with ls –lrt to display empty files and directories as shown below :
./empty.txt
test@localhost:~/unix find . -type d -empty
./empty_dir
//How to use grep command to print empty files and directories
test@localhost:~/unix ls -ltr | grep '\<0\>'
drwxr-xr-x+ 1 test Domain Users 0 Jun 15 11:43 empty_dir/
-rw-r--r-- 1 test Domain Users 0 Jun 15 11:44 empty.txt
test@localhost:~/unix find . -maxdepth 1 -size 0 -ls
90353467524120775 0 drwxr-xr-x 1 test Domain Users 0 Jun 15 11:43 .
9007199255261921 0 -rw-r--r-- 1 test Domain Users 0 Jun 15 11:44 ./empty.txt
19421773393554899 0 drwxr-xr-x 1 test Domain Users 0 Jun 15 11:43 ./empty_dir
test@localhost:~/unix find . -empty -delete
test@localhost:~/unix ls -lrt
total 1.0K
-rw-r--r-- 1 test Domain Users 118 Aug 4 2011 contacts.txt
test@localhost:~/unix find . -empty | xargs rm -r
test@localhost:~/unix find . -empty -type d -exec rm -r {} \;
find: `./empty_dir': Not a directory
Top 10 examples of chmod command in Unix
How to convert IP address to hostname in Unix
10 tips to work fast in Unix and Linux
10 Example of tar command in Unix and Linux
Unix command tutorials for beginners
How to update soft link in one command in Unix