How to find or identify empty directories or files in Linux?
It can be done easily with find command itself.
Here's the syntax and how to test.
mkdir test_empty
cd test_empty
create some dummy directories:
mkdir {dummydir1,dummydir2,dummydir3}
then create some empty files:
touch {file1empty,file2empty,file3empty}
To find empty directories:
find . -type d -empty
To find empty files:
find . -type f -empty
All directories and files will be shown since they are empty.
Add some text to the file:
echo "Test" > file1empty
Run again the command:
find . -type f -empty
file1empty will not be on the list since the file has some text.
Move the file1empty to dummydir1.
mv file1empty dummydir1
Run the command to find empty directories:
find . -type d -empty
dummydir1 will not be displayed since file1empty is inside of it.
How to remove or delete empty directories or files?
In production or any environment, make sure you know what you are doing.
In a testing environment, it can be done like this:
find . -type d -empty -exec rmdir {} \; 2>/dev/null
To delete empty files:
find . -type f -empty -exec rm {} \;
Above can be put to crontab to schedule and auto delete empty files and directories, however, do it sensibly.
That's it..till next time..
Trust God in all His ways. Connect to Jesus Daily.
Fiat Voluntas Tua | Catholic Prayers & Quotes
Comments
Post a Comment