In shell scripting, to locate and delete files older than a specific date, the find command is commonly used. This command is highly versatile for identifying files and directories that meet certain criteria, and it can be paired with the -exec option to perform actions on these items. Below is a practical example demonstrating how to delete files older than 30 days.
-
Determine the Target Directory: First, identify where the files you intend to operate on are stored. For this example, assume the directory is
/path/to/directory. -
Write the Script:
bash#!/bin/bash # Define directory path TARGET_DIR="/path/to/directory" # Define days, here 30 days as an example DAYS=30 # Locate and delete files older than 30 days find $TARGET_DIR -type f -mtime +$DAYS -exec rm -f {} + echo "All files older than $DAYS days in $TARGET_DIR have been deleted."
Explanation:
find $TARGET_DIR -type f:Identifies all files (excluding directories) within the specified directory$TARGET_DIR.-mtime +$DAYS:mtimerefers to the last modification time of the file content, and+$DAYSspecifies files modified more than$DAYSdays ago.-exec rm -f {} +:Executes therm -fcommand on each found file for deletion. Here,{}acts as a placeholder for the file name identified byfind, and+indicates thatrmis executed once for multiple files.
- Run the Script: Save the script to a file, such as
delete_old_files.sh, grant execute permissions, and execute it:
bashchmod +x delete_old_files.sh ./delete_old_files.sh
This script safely removes all files in the specified directory that have not been modified for over 30 days. Adjust TARGET_DIR and DAYS as needed for your use case. To avoid accidental deletion of critical files, always test the script in a non-production environment before deployment.