File: //ibin/cleanup-files
#########################################################################################################
#!/bin/bash
# cleanup
# Written by - Jack Sasportas - Jack@innovativeinternet.com
#
# Erase old files/folders based on value in the DAYS field
#
# expecting folder value via command line
# /ibin/cleanup /path/to/folder
#
#
# 6/8/20 - added parameter for DAYS
# 2/1/2023 - added some safety protocols to ensure you didn't execute in /etc/ or / changed to xargs
# - to improve performance on the delete
#
#########################################################################################################
VER="v 1.3F"
DAYS=80 #Delete backups after X DAYS
FIND=/usr/bin/find;
RM=/bin/rm;
REDonWHITE='\e[1;41;39m'
CLEAR='\033[0m\n'
PROTECTED_DIRS_FILE="/ibin/protected_dirs.txt"
if [ $# -gt 2 ]; then
echo "Usage: $0 [folder] [days]"
exit 1
fi
if [ $# -eq 0 ]; then
FOLDER=$(pwd)
else
FOLDER=$1
fi
# Ensure that the restricted directories are not used
if [ -f $PROTECTED_DIRS_FILE ]; then
while read -r dir; do
if [ "$FOLDER" == "$dir" ]; then
echo "Error: $dir is a restricted directory and cannot be used."
exit 1
fi
done < "$PROTECTED_DIRS_FILE"
else
echo "Error: $PROTECTED_DIRS_FILE does not exist."
exit 1
fi
# Set Days to 2nd Parameter
if [ $# -eq 2 ]; then
DAYS=$2
fi
echo -e "$REDonWHITE CleanupFiles $VER\\n"
echo "Deleting files older than $DAYS days in $FOLDER"
echo -e "$CLEAR"
# Use xargs to efficiently delete files in batches
$FIND $FOLDER -maxdepth 5 -type f -mtime +$DAYS -print0 | xargs -0 $RM -v -f