Here is a Bash script that removes only empty directories, including those nested within other directories. If a directory contains any files or non-empty directories, it will remain untouched.
#!/bin/bash
# Check if a directory path is provided
if [ -z "$1" ]; then
echo "Usage: $0 /path/to/directory"
exit 1
fi
# Function to remove empty directories
remove_empty_dirs() {
local dir="$1"
# Find and remove empty directories, working from the deepest subdirectories up
find "$dir" -type d -empty -delete
}
# Call the function with the provided directory path
remove_empty_dirs "$1"
How to Use:
- Save the script as
remove_empty_dirs.sh
. - Make it executable:
chmod +x remove_empty_dirs.sh
- Run the script with the directory path as an argument:
./remove_empty_dirs.sh /path/to/directory
Explanation:
find "$dir" -type d -empty -delete
: This command finds all empty directories in the given directory and deletes them. The-empty
flag ensures that only empty directories are targeted, and-delete
removes them.- The script ensures that only empty directories are removed, working from the deepest level upwards, so no directories with content are affected.