Data rotation and cleanup help keep your Raspberry Pi's storage tidy and free from old files. This stops your device from running out of space and keeps things organized.
0
0
Data rotation and cleanup in Raspberry Pi
Introduction
When your Raspberry Pi collects logs or data files continuously and you want to keep only recent ones.
If you run a program that saves backups regularly and you want to delete old backups automatically.
When you want to save disk space by removing files older than a certain number of days.
To keep your system fast and avoid clutter by cleaning temporary files regularly.
Syntax
Raspberry Pi
# Example bash script for data rotation and cleanup # Delete files older than 7 days in /home/pi/data find /home/pi/data -type f -mtime +7 -exec rm {} \; # Move current log to backup and create new log mv /home/pi/log.txt /home/pi/log_backup_$(date +%F).txt > /home/pi/log.txt
find command searches files by age and deletes them.
Using mv with $(date +%F) adds the current date to the backup filename.
Examples
This removes log files older than 30 days to save space.
Raspberry Pi
# Delete files older than 30 days in /var/log find /var/log -type f -mtime +30 -exec rm {} \;
This renames the current log with today's date and creates a new empty log.
Raspberry Pi
# Rotate a log file daily
mv /home/pi/app.log /home/pi/app_$(date +%Y-%m-%d).log
> /home/pi/app.logThis deletes files that have zero size, cleaning up useless files.
Raspberry Pi
# Remove empty files in a folder find /home/pi/data -type f -empty -delete
Sample Program
This script deletes files older than 5 days in the data folder and rotates the log file by renaming it with the current date. Then it creates a new empty log file.
Raspberry Pi
#!/bin/bash # Directory to clean DATA_DIR="/home/pi/data" # Delete files older than 5 days find "$DATA_DIR" -type f -mtime +5 -exec rm {} \; # Rotate log file LOG_FILE="/home/pi/myapp.log" BACKUP_LOG="/home/pi/myapp_$(date +%F).log" mv "$LOG_FILE" "$BACKUP_LOG" > "$LOG_FILE" echo "Cleanup done. Old files removed and log rotated."
OutputSuccess
Important Notes
Always test your cleanup commands on a small folder first to avoid deleting important files.
Use cron jobs to run cleanup scripts automatically at regular times.
Back up important data before running automatic deletion scripts.
Summary
Data rotation and cleanup keep your Raspberry Pi storage organized and free from old files.
Use find to delete files older than a certain number of days.
Rotate logs by renaming them with dates and creating new empty files.