Skip to content

Instantly share code, notes, and snippets.

@garvit-exe
Created September 13, 2024 14:35
Show Gist options
  • Save garvit-exe/39539afd850f9f81ac18c3bdfadcfaf1 to your computer and use it in GitHub Desktop.
Save garvit-exe/39539afd850f9f81ac18c3bdfadcfaf1 to your computer and use it in GitHub Desktop.
This script backs up important files, compresses them, and uploads them to a remote server via SSH while logging the entire operation.
#!/bin/bash
# Variables
SRC_DIRS="/var/www /home/user/documents /etc" # Directories to backup
BACKUP_NAME="backup_$(date +'%Y-%m-%d_%H-%M-%S').tar.gz" # Backup filename
BACKUP_DIR="/tmp/backups" # Temporary location for backup storage
REMOTE_USER="your_username"
REMOTE_HOST="your_remote_server.com"
REMOTE_DIR="/path/to/remote/backup/dir"
LOG_FILE="/var/log/backup.log"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Logging the start of the operation
echo "[$(date)] Starting backup process" >> "$LOG_FILE"
# Archive and compress the directories
echo "[$(date)] Archiving directories: $SRC_DIRS" >> "$LOG_FILE"
tar -czf "$BACKUP_DIR/$BACKUP_NAME" $SRC_DIRS >> "$LOG_FILE" 2>&1
if [ $? -eq 0 ]; then
echo "[$(date)] Successfully created archive: $BACKUP_NAME" >> "$LOG_FILE"
else
echo "[$(date)] Error during archive creation!" >> "$LOG_FILE"
exit 1
fi
# Uploading the backup to the remote server
echo "[$(date)] Uploading archive to $REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR" >> "$LOG_FILE"
scp "$BACKUP_DIR/$BACKUP_NAME" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR" >> "$LOG_FILE" 2>&1
if [ $? -eq 0 ]; then
echo "[$(date)] Successfully uploaded archive to remote server" >> "$LOG_FILE"
else
echo "[$(date)] Error during upload to remote server!" >> "$LOG_FILE"
exit 1
fi
# Cleaning up local backup files
rm -f "$BACKUP_DIR/$BACKUP_NAME"
echo "[$(date)] Local backup file removed: $BACKUP_NAME" >> "$LOG_FILE"
# Logging completion
echo "[$(date)] Backup process completed successfully" >> "$LOG_FILE"
@garvit-exe
Copy link
Author

Make sure to make the script executable after saving it:

chmod +x backup_and_upload.sh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment