Delete More Than x Days Data in Linux Shell Script | Arkit
Write Your Own Method of Script using the below scenario and comment. Recently i came across this situation where i could not able to delete more than x days data using the find command due to -mtime is not matching.
Delete More than x Days Data
Scenario: Every day from Monday to Friday one directory will be created under /fullbackup/dailybackup/YYYY-MM-DD and it will move same dirctory to its parent directory everyday midnight /fullbackup/archive/, However Saturday, Sunday and Monday directories will move to /fullbackup/archive path every Monday evening.
Directory Names Example:
$ ls -ltrdrwxrwxrwx 2 ravi backupgroup 4096 Dec 29 12:25 2018-12-28
drwxrwxrwx 2 ravi backupgroup 4096 Dec 29 12:25 2018-12-29
Question: I would like to delete directories older than two days from /fullbackup/archive path. How do you do it using any scripting methods?
Problem Statement: I was trying to use find . -type d -mtime +4 -exec rm -rf {} \;. This command does not work because the modified date for all moved directories on Monday is the same. I can’t differentiate the last three directories modified date which is -mtime.
How Do you solve it.?? Write a Shell Script to accomplish this task. Should run through crontab and clear directories older than two days.
Shell Script to Delete More than x Days Data
#!/bin/bash
## Delete the Directories based on Directory name validation
ls -ltr /fullbackup/archive/ |awk '{print $9}' > /scripts/dirs
for i in `cat /scripts/dirs`; do
STARTTIME=$(date +%s -d"$i 00:00:00")
ENDTIME=$(date +%s)
echo $((ENDTIME-STARTTIME)) | awk '{print int($1/60)}' > /scripts/value
COUNT=`cat /scripts/value`
if [ $COUNT -gt 2880 ]; then
echo "Directory /fullbackup/archive/$i is Older than 2Days Deleting" >> /scripts/joblog.log
rm -rf /fullbackup/archive/$i
fi
done
Explanation
- ls -ltr line will list all the directories on the full backup path and print 9th column using awk and store output to file
- For loop is using output file and prints one directory name YYYY-MM-DD
- STARTTIME will convert directory name to EPOC time by adding 00:00:00 Hours, Minutes, and Seconds
- ENDTIME prints current date & time in EPOC time format
- echo statement will minus End time – start time and print value into minutes
- COUNT variable is assigned with minutes value
- if statement will validate value is more than 2880 minutes means more than two days of time
- if the value is more than 2880 then rm will delete the directory
Solve the scenario using your own method and post the solution in a comment. Thanks.
Note: Above script works only when the directory name is Year-Month-Date otherwise it will give an error message.
Related Articles
Thanks for Your Wonderful Support and Encouragement
More than 40,000 techies are part of our ARKIT community. Join us today and keep learning Linux, Cloud, Storage, DevOps, and IT technologies.