Project # 1 - Basic Backup Shell Script

Project # 1 - Basic Backup Shell Script

Simple Project to Automate your Backups using Shell Script

In this project we'll be creating a simple yet effective backup shell script! In today's digital age, data is paramount, and ensuring its safety through regular backups is crucial. With this shell script, you'll be able to automate the process of backing up your important files and directories, giving you peace of mind knowing that your data is secure.

Script:

#!/bin/bash
# Source directory to be backed up
source_directory="/path/to/source"
# Destination directory (external drive or network location)
destination_directory="/path/to/destination"
# Log file to record backup details
log_file="/path/to/backup.log"
# Perform the backup using rsync
rsync -av --delete "$source_directory" "$destination_directory" >> "$log_file" 2>&1
# Timestamp for the log
time_stamp=$("date")
echo "Backup completed on: $time_stamp" >> "$log_file"

Explanation:

  • #!/bin/bash : This is the shebang line. It is used to tell the operating system which shell to use for executing the script.

  • source_directory="/path/to/source" : source_directory is a variable where the location of the directory or file will be stored that we want to backup.

  • destination_directory="path/to/destination" : destination_directory is a variable where the location will be stored where we want our backup to be stored. This location can be in the same system and also on the internet.

  • log_file="path/to/backup.log" : log_file is a variable where the location of file with the extension .log will be stored. This file is made to store that when the last backup was done or the backup was successful or not.

  • rsync -av --delete "$source_directory" "$destination_directory" >> "$log_file" 2>&1 : The rsync command performs the backup. It copies files from the source directory to the destination directory, ensuring that only changed or new files are transferred. The --delete option removes files from the destination if they are no longer present in the source. $ is used with the variable names to take the value placed in the variable. The output of the rsync command will be saved in the log file that we made, also if there will be any error while backup that error line will also be saved into the log file.

  • time_stamp=$("date") : time_stamp is a variable where the date is stored.

  • echo "Backup completed on: $time_stamp" >> "$log_file" : echo will print the line into the log file.

Running the Script: