DEV Community

Cover image for Script to clean out files in dir and have a note of deleted files in deleted_files.log
Sunil Vijay
Sunil Vijay

Posted on

Script to clean out files in dir and have a note of deleted files in deleted_files.log

Today we'll discuss some scenarios in bash scripting.

Problem Statement:

Let's say I have a directory in my Linux driver name called movies. And I'm downloading a film from the torrent daily to relax. So in an average round, my machine would have a bottleneck of disk space. So I need to delete my old files which were downloaded past 2 days ago. And also I need to delete files and copy the name and date of the deleted files in a log file for my later check what has been deleted.
i.e) /home/user/movies/

Note: take this just as an example and implement it in any kinda scenario.

Solution:
Alt Text

Also, Discuss some of your thoughts in comments, if I'm wrong, suggest some best practices. Ideas are always welcome. Thanks in advance....

Top comments (3)

Collapse
 
bobbyiliev profile image
Bobby Iliev

Looks good! Can you also share the code itself here as well so people could copy it easier?

Collapse
 
sunilvijay profile image
Sunil Vijay • Edited

TIMESTAMP=date +%F

echo "Auto Generate Log files"
find /home/ubuntu/audios/ -name 'audio*' -mmin +2880 -exec bash -c ' echo "{} - " date -r {} rm -rf {} ' \; | xargs > deleted-files-$TIMESTAMP.log
echo "Log Generated Successfully"

Collapse
 
sunilvijay profile image
Sunil Vijay

Thanks Bobby. The code is above in the snippet.