Mini Project - To Automate the Backup of your Work in Shell Script

Mini Project - To Automate the Backup of your Work in Shell Script

One of the simplest ways to back up a system is using a shell script. For example, a script can be used to configure which directories to back up and pass those directories as arguments to the tar utility, which creates an archive file.

First, create a new file with a .sh extension, for example, "backup_script.sh".

Open the file in your favourite text editor, and enter the following code:

#!/bin/bash

Define variables

backup_dir="/path/to/backup/directory"
backup_file="backup-$(date +%Y-%m-%d-%H-%M-%S).tar.gz"
source_dir="/path/to/source/directory"

Create the backup directory if it doesn't exist

mkdir -p "$backup_dir"

Create backup file

tar -czvf "$backup_dir/$backup_file" "$source_dir"

Remove old backups (keep only the last 7 days)

find "$backup_dir" -type f -mtime +7 -delete

Save the file and exit the editor.

Make the script executable by running the following command in the terminal:

chmod +x backup_script.sh

Now, you can schedule the script to run automatically using cron. Open the crontab file by running the following command:

crontab -e

Add the following line at the end of the file to schedule the script to run every day at midnight

0 0 * * * /path/to/backup_script.sh

Save the crontab file and exit the editor. That's it! Now the script will run every day at midnight and create a compressed backup of the specified directory. The script will also delete any backups older than 7 days to save disk space.

Did you find this article valuable?

Support Aakash Bhatt by becoming a sponsor. Any amount is appreciated!