BASH

Automate File Backup with Timestamps

Learn to create a robust bash script for automating file backups, appending timestamps to directories for easy versioning and recovery.

#!/bin/bash

SOURCE_DIR="/path/to/your/data"
BACKUP_ROOT="/path/to/your/backups"

# Generate a timestamp for the backup directory
DATE=$(date +"%Y-%m-%d_%H-%M-%S")
DEST_DIR="$BACKUP_ROOT/backup_$DATE"

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

# Perform the recursive copy
cp -r "$SOURCE_DIR" "$DEST_DIR"

# Check if the copy was successful
if [ $? -eq 0 ]; then
    echo "Backup of $SOURCE_DIR to $DEST_DIR successful."
else
    echo "Backup failed!"
    exit 1
fi
How it works: This script automates creating a timestamped backup of a specified source directory. It defines source and backup root paths, generates a unique directory name using the current date and time, creates the destination directory, and then recursively copies the source directory's contents to it. An `if` statement checks the exit status of the `cp` command to report success or failure, providing a simple yet effective local backup solution.

Need help integrating this into your project?

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

Hire DigitalCodeLabs