Data loss is an unfortunate and very real risk in any organizational environment. Losing critical data due to accidental deletion can have severe consequences for businesses. Therefore, it is essential for organizations to establish a reliable backup strategy to mitigate the risks of data loss.
As a vital component of the backup strategy, regularly backing up critical files is a crucial task for DevOps Engineers. By doing so, they ensure that important data is preserved and can be restored in case of any unexpected incidents, such as system failures, human errors, or cyber-attacks.
Also, taking backups every day manually is a repetitive task and this can be automated using corn.
So here, I'll be demonstrating a step-by-step process that we can follow to make a simple cron job that backs up your script file weekly.
The prerequisite is that you should know a basic of corn job that you can read here.
First, we locate our script file where all the scripts are written and stored. For me, it is in /home/ubuntu/scripts.
Now, we'll write a backup script. This will make the archive of files at a particular place that needs to be backed up. Below is the script.
#!/bin/bash
src=/home/ubuntu/scripts
tgt=/home/ubuntu/backups
file_name=$(date | xargs | awk '{print $3"-"$2"-"$6}')
tar -czvf $tgt/$file_name.tar.gz $src
echo "Backup Complete"
Here,
scr is the location of source files that need to be backed up
tgt is the location where the backup file will be kept
file_name is the variable that I'll be using as the name of the backup file (Here
date | xargs | awk '{print $3"-"$2"-"$6}'
will give the current date)tar -czvf $tgt/$file_name.tar.gz $src
this will create an archive file of the files present at scr at location tgt with name <file_name>.tar.gzecho will print "Backup Complete", once the backup script runs.
save this script by name backup.sh
Let's test it out by running the script by the below command.
Command: . /home/ubuntu/scripts/backup.sh
Our script is working fine and it is taking backups as expected. Now we just have to schedule it using cron. For that, we need to append our schedular command in the crontab.
You can open the crontab using the command crontab -e
Command: 0 8 * * 1 . /home/ubuntu/scripts/backup.sh
Now, every Monday all the files that are in the scripts folder will be backed up in the backup folder.
Please like this blog if it was able to add value to your knowledge.
I would appreciate your feedback, as it is valuable to me in improving my blog content.
I would love to connect with you on LinkedIn: Abhinav Pathak