Created
July 1, 2024 19:46
-
-
Save jimdiroffii/231dab477d35152d12f3e9bec07debe4 to your computer and use it in GitHub Desktop.
Recursively delete all empty files and directories in a path. Starts as deeply as possible, removes all files first, then the parent directory if empty.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Recursive Delete - All empty files and directories | |
# Check if a directory is provided | |
if [ -z "$1" ]; then | |
echo "Usage: $0 [directory]" | |
exit 1 | |
fi | |
# Starting directory | |
DIR=$1 | |
# Function to remove empty files and directories | |
remove_empty() { | |
local directory=$1 | |
# Find and delete empty files in the deepest directories first | |
find "$directory" -depth -type f -empty -delete | |
# Find empty directories and delete them, deepest first | |
find "$directory" -depth -type d -empty -delete | |
} | |
# Exporting the function to be available in the subshell spawned by find | |
export -f remove_empty | |
# Use find to apply the remove_empty function to each directory | |
find "$DIR" -depth -type d -exec bash -c 'remove_empty "$0"' {} \; | |
# Final cleanup in case the top directory is now empty | |
find "$DIR" -depth -type d -empty -delete |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment