← Back to all snippets
BASH

Automate Git Repository Backup

Create a timestamped, compressed backup of a local Git repository, ideal for safeguarding project history or migrating repositories.

#!/bin/bash

REPO_PATH="/path/to/your/git/repo"
BACKUP_DIR="/path/to/your/backups"
TIMESTAMP=$(date +"%Y%m%d%H%M%S")
BACKUP_FILENAME="repo_backup_${TIMESTAMP}.tar.gz"

if [ ! -d "$REPO_PATH" ]; then
    echo "Error: Repository path '$REPO_PATH' does not exist."
    exit 1
fi

mkdir -p "$BACKUP_DIR"

tar -czf "${BACKUP_DIR}/${BACKUP_FILENAME}" -C "$(dirname "$REPO_PATH")" "$(basename "$REPO_PATH")"

if [ $? -eq 0 ]; then
    echo "Git repository '$REPO_PATH' backed up successfully to '${BACKUP_DIR}/${BACKUP_FILENAME}'"
else
    echo "Error: Failed to backup Git repository '$REPO_PATH'."
fi
How it works: This script creates a gzipped tar archive of a specified Git repository. It first defines the repository path, backup directory, and generates a timestamp for unique backup filenames. It checks if the repository exists and creates the backup directory if needed. Finally, it uses `tar` to create the compressed archive and provides status messages, making it useful for safeguarding project history.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs