SoFunction
Updated on 2025-03-10

The shell cleans up old files before the specified number of days in the specified directory

Preface

We often generate a lot of temporary files when running some services on the server.
However, some temporary files can easily fill the entire disk by processing them from time to time;
Therefore, it is necessary to clean up regularly. Based on this requirement, we can create a script combinationcrontabOr service schedules to use these;

Script implementation

#!/bin/bash
# cleanup_old_files - Clean up old files before the specified number of days in the specified directory# $1: Directory name# $2: Days# $3: (optional) keyword to match file namesfunction cleanup_old_files() {
    local dir="$1"     # Directory name    local days="$2"    # days    local keyword="$3" # Keywords matching filename    # Parameter validity check    if [ -z "$dir" ]; then
        echo "Error: Directory parameter is empty."
        return 1
    fi
    if [ ! -d "$dir" ]; then
        echo "Error: Directory $dir does not exist."
        return 1
    fi
    if ! [[ "$days" =~ ^[0-9]+$ ]]; then
        echo "Error: The number of days parameter is invalid."
        return 1
    fi
    # If the number of days is not specified, the default is the same day    if [ -z "$days" ]; then
        days=0
    fi
    # Build a lookup command to distinguish based on the value of $days    if [ "$days" -eq 0 ]; then
        find_cmd="find -L \"$dir\" -type d -o -type f -mtime 0"
    else
        find_cmd="find -L \"$dir\" -type d -o -type f -mtime +$days"
    fi
    # If a keyword is specified, add it to the search command    if [ -n "$keyword" ]; then
        find_cmd+=" -name \"*$keyword*\""
    fi
    # Print the full command    echo "Execute the command: $find_cmd"
    # Perform search and delete files    if [ "$days" -eq 0 ]; then
        echo "Cleaning up the directory $dir Created on the same day$(if [ -n "$keyword" ]; then echo "Contains the keyword $keyword"; else echo "all "; fi)document..."
    else
        echo "Cleaning up the directory $dir middle $days Created a day ago$(if [ -n "$keyword" ]; then echo "Contains the keyword $keyword"; else echo "all "; fi)document..."
    fi
    # Delete the found file via -exec rm -rf {} +    if eval "$find_cmd -exec rm -v -rf {} +" >/dev/null; then
        if [ "$days" -eq 0 ]; then
            echo "Deleted当天的旧document."
        else
            echo "Deleted $days 天之前的旧document."
        fi
    else
        echo "Deletion failed."
        return 1
    fi
}
# Example usage# cleanup_old_files "/path/to/directory" 30 "log"
# cleanup_old_files "/path/to/directory" 0 "log"

Summarize

Note 1: When mtime is 0

It is worth noting thatmtimeWhen it is 0, we want to simulate the day, and we cannot use modifiers (+/-);
The execution performance of Debian and MacOS is that there is no error, but there is no operation, so a distinction is made in the code;

Note 2: When /tmp is a soft chain

iffindIf you want to retrieve the contents in the command, please remember to bring it-L, otherwise nothing can be retrieved;

# Under mac tmp is a soft link to /private/tmpls -l /tmp
lrwxr-xr-x@ 1 root  wheel  11 Dec  2 19:37 /tmp -> private/tmp

Bring it with you-LAfter that, it will be compatible with both Linux and MacOS platforms, making it convenient for local debugging and testing;

The general purpose of this parameter is to search for recursively, so symbolic links can also be retrieved;
If you don't have one, you will only look for hard links, and the symbolic links will be ignored directly.

This is the article about shell cleaning old files before the specified number of days in the specified directory. For more relevant shell cleaning content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!