BASH

Create Timestamped Directory Backup with Tar

Safely backup your web project directories by creating a timestamped gzipped tar archive, ensuring you have a restore point before major changes.

#!/bin/bash

SOURCE_DIR="./my_web_project"
BACKUP_DIR="./backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/my_web_project_backup_$DATE.tar.gz"

mkdir -p "$BACKUP_DIR"

if [ ! -d "$SOURCE_DIR" ]; then
  echo "Error: Source directory '$SOURCE_DIR' not found."
  exit 1
fi

echo "Creating backup of '$SOURCE_DIR' to '$BACKUP_FILE'..."
tar -czf "$BACKUP_FILE" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

if [ $? -eq 0 ]; then
  echo "Backup successful!"
  echo "Backup file: $(realpath "$BACKUP_FILE")"
else
  echo "Backup failed!"
  exit 1
fi
How it works: This script automates the process of creating a timestamped backup of a specified source directory. It first creates a backup directory if it doesn't exist and validates the source directory. Then, it uses `tar -czf` to create a gzipped tar archive of the source directory, saving it with a unique name based on the current date and time. It provides success or failure messages upon completion.

Need help integrating this into your project?

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

Hire DigitalCodeLabs