Home / Clayi CodeScripts / Scripts / Bash Script to Backup and Compress Directories with Timestamp

Bash Script to Backup and Compress Directories with Timestamp

Bash Script to Backup and Compress Directories with Timestamp
  • Category Scripts
  • Type Command
  • Platform Linux
  • Language Bash
  • Price Free
  • Views 1 264
  • Comments 0
View Resource
Bash Script to Backup and Compress Directories with Timestamp

The Crucial Importance of Regular Directory Backups

Data loss is an inevitable reality of working in technology. Whether caused by accidental deletion, hardware failure, or malicious cyber attacks, losing important configuration files, web application data, or personal documents can be absolutely devastating. Implementing a reliable backup strategy is the single most effective way to protect your valuable digital assets. The script featured in this "Bash Script to Backup and Compress Directories with Timestamp" guide offers a lightweight, automated, and highly secure method to preserve your essential directories without relying on expensive third-party software.

Understanding the Timestamped Backup Bash Script

This powerful Bash script is specifically designed to take a designated source directory, compress it into a highly efficient archive file, and save it in a secure location. By utilizing native Linux command-line tools, the script bypasses the need for bloated graphical interfaces, making it incredibly fast and ideal for headless servers. It dynamically appends a unique timestamp to every single backup file it creates, ensuring that your previous archives are never accidentally overwritten during subsequent backup runs.

How the Script Handles Source and Destination Variables

At the very beginning of the script, two primary variables are established to dictate where data comes from and where it goes. The SOURCE_DIR="$1" captures the very first argument provided by the user, which is the folder that needs to be backed up. The BACKUP_DIR="${2:-./backups}" introduces a clever fallback mechanism; if the user provides a second argument, it sets that as the destination. If no destination is specified, it gracefully defaults to creating a local directory named backups right in the current working path.

Generating Unique Timestamps for Safe Archiving

To prevent newer backups from silently overwriting older ones, generating unique filenames is an absolute necessity. The line TIMESTAMP=$(date +"%Y%m%d_%H%M%S") executes the Linux date command to generate a precise string representing the current year, month, day, hour, minute, and second. This timestamp is later seamlessly injected into the final output filename, guaranteeing that every single backup archive is distinct, chronologically organized, and incredibly easy to locate when a critical system restore is required.

Ensuring Error Prevention with Directory Checks

A poorly written script can cause serious issues if it attempts to execute without the correct parameters. This script employs a robust fail-safe mechanism right from the start. The if statement checks whether the SOURCE_DIR variable is empty. If the user accidentally runs the script without specifying a target directory, the script instantly echoes an error message and terminates via exit 1. Additionally, the mkdir -p "$BACKUP_DIR" command intelligently ensures the destination folder actually exists before attempting to write data to it.

The Power of the Tar Command for Compression

The true heavy lifting of this script is performed by the venerable tar command, which stands for Tape Archive. The flags -czf instruct the system to Create a new archive, Zip it using gzip compression to save valuable disk space, and output it to a specific File. The syntax tar -czf "$BACKUP_FILE" -- "$SOURCE_DIR" safely bundles up the entire source directory structure into a single .tar.gz file. The double dashes (--) add an extra layer of security, ensuring that directory names starting with hyphens are not mistakenly treated as command flags.

Reviewing the Final Output and Success Message

Once the heavy compression process is fully completed, the script provides immediate, reassuring feedback to the user. The final echo command outputs a clear "Backup created successfully" message, along with the absolute path and exact filename of the newly created archive. This terminal output is incredibly useful for logging purposes. If you redirect the output of this script into a system log file, you will maintain a perfect, easily searchable audit trail of exactly when and where every single backup was created.

How to Schedule Automated Backups Using Cron Jobs

While running this script manually is great for one-off snapshots, its true potential is unleashed when you automate it. By integrating this script with Linux Cron Jobs, you can schedule it to run automatically every night, week, or month. Simply type crontab -e in your terminal and add a line like 0 2 * * * /path/to/backup.sh /var/www/html /backup/drive. This tells your server to seamlessly back up your web directory every morning at 2:00 AM, granting you complete peace of mind that your data is always safe and recoverable.

Popularity
0%
  • Votes: 10
  • Comments: 0

Help

Can't download assets? How to use Clayi Assets Assets not working? Can't copy? How to use Clayi Code Snippet not working?

Free Bash Script to Backup and Compress Directories with Timestamp Command Download

#!/usr/bin/env bash
# Create a timestamped tar.gz backup of a specific directory
# Usage: ./backup.sh [directory_to_backup] [backup_destination]

SOURCE_DIR="$1"
BACKUP_DIR="${2:-./backups}"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

# Check if the source directory argument is provided
if [ -z "$SOURCE_DIR" ]; then
    echo "Error: Specify a source directory."
    exit 1
fi

# Create the backup destination directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Define the final backup file path
BACKUP_FILE="$BACKUP_DIR/backup_$(basename "$SOURCE_DIR")_$TIMESTAMP.tar.gz"

# Compress and archive the target directory safely
tar -czf "$BACKUP_FILE" -- "$SOURCE_DIR"

echo "Backup created successfully: $BACKUP_FILE"

Download Assets
Wait 10 sec
Free file download — fast & secure!
Download this open-source asset for free on Clayi Assets. Direct CDN link after a short wait — no account required.

New Resources

Popular Resources

There are no comments yet :(

Bash Script to Backup and Compress Directories with Timestamp
Tell us what you think about "Bash Script to Backup and Compress Directories with Timestamp"
Information
Users of Guests are not allowed to comment this publication.