乐闻世界logo
搜索文章和话题

How do you find and delete files older than a specific date in a shell script?

1个答案

1

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.

  1. 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.

  2. 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 +$DAYSmtime refers to the last modification time of the file content, and +$DAYS specifies files modified more than $DAYS days ago.
  • -exec rm -f {} +:Executes the rm -f command on each found file for deletion. Here, {} acts as a placeholder for the file name identified by find, and + indicates that rm is executed once for multiple files.
  1. Run the Script: Save the script to a file, such as delete_old_files.sh, grant execute permissions, and execute it:
bash
chmod +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.

2024年8月14日 17:19 回复

你的答案