Recursively Deleting Empty Files and Directories under Linux
Sometimes, we have the need to delete empty files and empty directories under Linux.
This happens, for example, when we want to restart an experiment with moptipy.
Here I post a small Bash script that you may store as file deleteZeroSizeFiles.sh.
It will do exactly that:
It will search the current directory and all subdirectories for empty files, i.e., files of size zero.
It will delete all of them.
Then, it will recursively look for empty directories, i.e., directories that do not contain files or other directories.
It will delete them as well.
All files and directories that get deleted are also printed, so you can see what happened.
Here you can download this script and the complete collection of my personal scripts is available here.#!/bin/bash
# This script deletes empty files (= files with size 0) an empty directories
# in the current directory recursively.
# Turn on strict error handling, so that the script fails as soon as something goes wrong.
set -o pipefail # trace ERR through pipes
set -o errtrace # trace ERR through 'time command' and other functions
set -o nounset # set -u : exit the script if you try to use an uninitialized variable
set -o errexit # set -e : exit the script if any statement returns a non-true return value
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): Deleting all empty files in current directory recursively."
find . -type f -empty -delete -print
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): Deleting all empty directories in current directory recursively."
find . -type d -empty -delete -print
echo "$(date +'%0Y-%0m-%0d %0R:%0S'): Finished cleaning up empty files and directories."