Skip to content

Instantly share code, notes, and snippets.

@joho1968
Created July 10, 2024 07:40
Show Gist options
  • Save joho1968/714de1d2b11b15d7074329ba9171619a to your computer and use it in GitHub Desktop.
Save joho1968/714de1d2b11b15d7074329ba9171619a to your computer and use it in GitHub Desktop.
Remove matching items older than nn days with a minimum count threshold and simulation mode
#!/bin/bash
# Must be run by root
if [ "$EUID" -ne 0 ]; then
echo "This script must be run as root"
exit 1
fi
# Show script usage
usage() {
echo "Usage: $0 -d DIRECTORY -m FILE_MASK -a AGE [-t THRESHOLD] [-x MAX_DEPTH] [-r]"
echo " -d DIRECTORY Directory to search in"
echo " -m FILE_MASK File mask to match (e.g., '*.log')"
echo " -a AGE Minimum age of files and directories to delete (in days)"
echo " -t THRESHOLD (Optional) Minimum number of matching items to proceed with deletion (default: 1)"
echo " -x MAX_DEPTH (Optional) Maximum depth for the search"
echo " -r (Optional) If present, perform the actual deletion. Otherwise, simulate only."
exit 1
}
# Initialize the delete flag to false and threshold to 1
DELETE_FLAG=false
THRESHOLD=1
# Parse command line arguments
while getopts "d:m:a:t:x:r" opt; do
case $opt in
d) DIRECTORY=$OPTARG ;;
m) FILE_MASK=$OPTARG ;;
a) AGE=$OPTARG ;;
t) THRESHOLD=$OPTARG ;;
x) MAX_DEPTH=$OPTARG ;;
r) DELETE_FLAG=true ;;
*) usage ;;
esac
done
# Check if all mandatory parameters are provided
if [ -z "$DIRECTORY" ] || [ -z "$FILE_MASK" ] || [ -z "$AGE" ]; then
usage
fi
# Construct the find command
if [ -n "$MAX_DEPTH" ]; then
FIND_CMD="find \"$DIRECTORY\" -maxdepth $MAX_DEPTH -name \"$FILE_MASK\" -mtime +$AGE"
else
FIND_CMD="find \"$DIRECTORY\" -name \"$FILE_MASK\" -mtime +$AGE"
fi
# Execute the find command and store the result
MATCHING_ITEMS=$(eval $FIND_CMD)
# Count the number of matching items
MATCHING_COUNT=$(echo "$MATCHING_ITEMS" | grep -c '^')
# If the number of matching items is less than the threshold, do not delete
if [ "$MATCHING_COUNT" -lt "$THRESHOLD" ]; then
echo "Fewer than $THRESHOLD matching items found. No deletions performed."
exit 0
fi
# Print the matching items if any are found
if [ -n "$MATCHING_ITEMS" ]; then
echo "Matching items:"
echo "$MATCHING_ITEMS"
else
echo "No matching items found."
exit 0
fi
# Perform deletion if the delete flag is true
if [ "$DELETE_FLAG" = true ]; then
echo "$MATCHING_ITEMS" | xargs rm -rf
echo "Deleted $MATCHING_COUNT items."
else
echo "Simulation only. No deletions performed."
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment