Automated Backup & Recovery using Cron

Subrat YadavSubrat Yadav
2 min read

Access the code on GitHub

Today , I encountered another beginner friendly challenge, the task is to create a bash script that takes a directory path as a command-line argument and performs a backup of the directory. The script should create time-stamped backup folders and copy all the files from the specified directory into the backup folder.

Additionally, the script should implement a rotation mechanism to keep only the last 3 backups. This means that if there are more than 3 backup folders, the oldest backup folders should be removed to ensure only the most recent backups are retained. I also needed to implement a Cron-Job so that the backup should be created on daily basis.

As creating a backup was a easy task which I have done previously ( you can use tar or gzip whichever you prefer I used gzip for this one ) so I was cool with it but the challenge was how to delete/remove folders which are older. So I just google it out once again got the solution where you just need to list the folders then sort those in reverse order and keep the top 3, now to remove the folders which are not needed I just have to iterate over all the folder in the main backup folder using for loop and discard the folders which are not the desired ones.

Key Challenge was To remove the Older folders.

Then after doing this much task I just need to create a cron-job using crontab command to make this script run daily basis. If more complexities can be added do let me know it will help to me advance in this Learning journey. Thank you for reading.

0
Subscribe to my newsletter

Read articles from Subrat Yadav directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Subrat Yadav
Subrat Yadav