How to find and remove all empty files using shell command line

In this config you will learn how to find all empty files within a given directory using find the find command. Here is our sandbox directory /tmp/temp containing files from which some of them are empty:

.
โ”œโ”€โ”€ dir1
โ”‚ย ย  โ”œโ”€โ”€ dir2
โ”‚ย ย  โ”‚ย ย  โ”œโ”€โ”€ file3
โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ file4
โ”‚ย ย  โ”œโ”€โ”€ file2
โ”‚ย ย  โ””โ”€โ”€ file3
โ”œโ”€โ”€ file1
โ””โ”€โ”€ file2

2 directories, 6 files

Let’s first locate all empty files recursively starting from a current working directory using find command:

$ pwd
/tmp/temp
$ find  . -type f -empty
OR
$ find  /tmp/temp -type f -empty
./dir1/dir2/file4
./dir1/file3
./file2

The following linux command will search for all empty file only within a current working directory, that is, not recursively:

$ find  . -maxdepth 1 -type f -empty
./file2

To remove all empty files we will combine the find command with its exec option. The following linux command will remove all empty files found recursively:

$ find  . -type f -empty -exec rm "{}" \;
OR
$ find  /tmp/temp -type f -empty -exec rm "{}" \;
$ tree 
.
โ”œโ”€โ”€ dir1
โ”‚ย ย  โ”œโ”€โ”€ dir2
โ”‚ย ย  โ”‚ย ย  โ””โ”€โ”€ file3
โ”‚ย ย  โ””โ”€โ”€ file2
โ””โ”€โ”€ file1

2 directories, 3 files