LINUX | Delete Old Backup Folders

Thursday, April 25th, 2024 | Server
Last Modified: 2024-05-10



This script is designed to delete directories that are named with dates in the 'YYYYMMDD' format and are older than 30 days based on their names. The script assumes these directories are located directly under /mnt/backups/Files.

Initial Testing Script

First, test with a listing version to ensure it targets the right directories:

#!/bin/bash

# Define the base directory containing the date-named folders.
base_directory="/mnt/backups/Files"

# Calculate the date 30 days ago in YYYYMMDD format.
threshold_date=$(date -d "30 days ago" +%Y%m%d)

# Loop through each directory in the base directory.
find "$base_directory" -maxdepth 1 -type d -regextype posix-extended -regex ".*/[0-9]{8}" | while read -r directory; do
    # Extract the date part of the directory name.
    dir_name=$(basename "$directory")
    
    # Check if this directory name is a date older than the threshold.
    if [[ "$dir_name" -lt "$threshold_date" ]]; then
        echo "$directory"  # Initially, just echo the directory to see which ones would be deleted.
    fi
done

Enable Actual Deletion

If the initial test lists the correct directories, replace the echo "$directory" line with rm -rf "$directory" to enable actual deletion:

rm -rf "$directory"  # Be very careful with this command.

Note: Always be extremely cautious with rm -rf, as it permanently deletes files and directories without asking for confirmation. Always back up important data before running such scripts.




Input Action Output
A collection of snippets and links that have proven useful for development, programming, ColdFusion, Javascript, jQuery, PHP, Python, Dell, Minecraft, Apple, Mac, Windows, LINUX, Raspberry Pi, Adobe, CSS, and HTML.

©2024 Input Action Output