BASH
Simple Timestamped File and Directory Backup
A bash script to create timestamped backups of individual files or entire directories, compressing them into `.tar.gz` archives for safe storage.
#!/bin/bash
# Configuration
SOURCE="/var/www/mywebapp/config.js" # File or directory to backup (e.g., /etc/nginx/nginx.conf or /var/www/mywebapp)
BACKUP_DIR="/var/backups/mywebapp" # Directory where backups will be stored
TIMESTAMP=$(date +%Y%m%d%H%M%S)
FILENAME=$(basename "$SOURCE")
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Check if source exists
if [ ! -e "$SOURCE" ]; then
echo "Error: Source '$SOURCE' not found. Aborting backup."
exit 1
fi
# Perform backup based on source type
if [ -f "$SOURCE" ]; then
# Source is a file
echo "Creating timestamped backup of file: $SOURCE..."
# Create a backup with timestamp before the file extension
cp "$SOURCE" "$BACKUP_DIR/${FILENAME%.*}.$TIMESTAMP.${FILENAME##*.}"
if [ $? -eq 0 ]; then
echo "File backup successful: $BACKUP_DIR/${FILENAME%.*}.$TIMESTAMP.${FILENAME##*.}"
else
echo "Error: Failed to create file backup."
exit 1
fi
elif [ -d "$SOURCE" ]; then
# Source is a directory
echo "Creating compressed timestamped backup of directory: $SOURCE..."
# Create a compressed tar archive of the directory
tar -czf "$BACKUP_DIR/${FILENAME}_$TIMESTAMP.tar.gz" -C "$(dirname "$SOURCE")" "$(basename "$SOURCE")"
if [ $? -eq 0 ]; then
echo "Directory backup successful: $BACKUP_DIR/${FILENAME}_$TIMESTAMP.tar.gz"
else
echo "Error: Failed to create directory backup."
exit 1
fi
else
echo "Error: Source '$SOURCE' is neither a file nor a directory. Aborting."
exit 1
fi
How it works: This script provides a straightforward way to create timestamped backups of important files or entire directories. It dynamically determines if the source is a file or a directory. For files, it copies them, embedding a timestamp before the extension. For directories, it creates a compressed `.tar.gz` archive. This is crucial for safeguarding configurations, database dumps, or application source code on web servers.