In Linux, it is sometimes necessary to regularly delete files or directories that are outdated. The following script can be used for scheduled execution, and those who need it can use it directly.Script content (only deletes files under the directory)
#!/bin/bash# Path: /opt/testBASE_DIR="/opt/test"
# Get the year and month of last month (format: YYYY-MM)LAST_MONTH=$(date -d "$(date +%Y-%m-01) -1 month" +%Y-%m)
echo "[$(date '+%F %T')] Starting cleanup of files created in $LAST_MONTH under $BASE_DIR..."
# Iterate through directories under /opt/testfor dir in "$BASE_DIR"/*; do [ -d "$dir" ] || continue # Only process directories echo "Checking directory: $dir"
# Find and delete files created last month in this directory find "$dir" -type f -newermt "${LAST_MONTH}-01" ! -newermt "$(date -d "${LAST_MONTH}-01 +1 month" +%Y-%m-%d)" -print -delete
done
echo "[$(date '+%F %T')] Cleanup completed."
Script content (directly deletes directories)
#!/bin/bash# Base directory, replace with actualBASE_DIR="/opt/test"
# Get the year and month of last month (format: YYYY-MM)LAST_MONTH=$(date -d "$(date +%Y-%m-01) -1 month" +%Y-%m)
echo "[$(date '+%F %T')] Starting cleanup of subdirectories created in $LAST_MONTH under $BASE_DIR..."
# Iterate through directories under /opt/testfor dir in "$BASE_DIR"/*; do [ -d "$dir" ] || continue # Only process directories
# Get the creation time of the directory (usually approximated by ctime on Linux ext4) DIR_TIME=$(stat -c %y "$dir" | cut -d' ' -f1) # Directory creation date YYYY-MM-DD DIR_MONTH=$(date -d "$DIR_TIME" +%Y-%m)
if [ "$DIR_MONTH" == "$LAST_MONTH" ]; then echo "Deleting directory: $dir" rm -rf "$dir" fi
done
echo "[$(date '+%F %T')] Cleanup completed."
Set up <span>crontab</span> scheduled task
0 1 1 * * /bin/bash /opt/clean_last_month.sh >> /var/log/clean_last_month.log 2>&1