0
0
Bash Scriptingscripting~5 mins

Backup automation script in Bash Scripting

Choose your learning style9 modes available
Introduction

Backing up files automatically saves your important data without needing to remember to do it yourself.

You want to save copies of your work files every day.
You need to keep a backup of photos or documents on another drive.
You want to protect your data before making big changes to your computer.
You want to automate backups to save time and avoid mistakes.
Syntax
Bash Scripting
#!/bin/bash

# Define source and backup folder
SOURCE="/path/to/source"
BACKUP="/path/to/backup"

# Create backup folder if it doesn't exist
mkdir -p "$BACKUP"

# Copy files from source to backup
cp -r "$SOURCE"/. "$BACKUP"/

# Print success message
echo "Backup completed successfully."

Use mkdir -p to create the backup folder if it does not exist.

The cp -r command copies all files and folders recursively.

Examples
This example backs up your Documents folder to a USB drive.
Bash Scripting
# Backup Documents folder to external drive
SOURCE="$HOME/Documents"
BACKUP="/mnt/usbdrive/backup_documents"
mkdir -p "$BACKUP"
cp -r "$SOURCE"/. "$BACKUP"/
echo "Documents backup done."
This example adds the current date to the backup folder name to keep multiple backups.
Bash Scripting
# Backup Pictures folder with date in folder name
DATE=$(date +"%Y-%m-%d")
SOURCE="$HOME/Pictures"
BACKUP="$HOME/Backups/Pictures_$DATE"
mkdir -p "$BACKUP"
cp -r "$SOURCE"/. "$BACKUP"/
echo "Pictures backup for $DATE done."
Sample Program

This script copies everything from your Documents folder to a backup folder inside your home directory. It creates the backup folder if it doesn't exist and then copies all files and folders inside Documents.

Bash Scripting
#!/bin/bash

# Simple backup script

SOURCE="$HOME/Documents"
BACKUP="$HOME/Backup/Documents_backup"

# Create backup folder if missing
mkdir -p "$BACKUP"

# Copy all files and folders
cp -r "$SOURCE"/. "$BACKUP"/

# Confirm backup
echo "Backup completed successfully."
OutputSuccess
Important Notes

Make sure you have permission to read the source and write to the backup folder.

Running this script regularly can be automated using cron jobs on Linux.

Always test your backup script with sample files before relying on it.

Summary

Automate backups to save time and protect your data.

Use mkdir -p and cp -r to create folders and copy files.

Add dates to backup folders to keep multiple versions.