Bash Script to Backup Files Easily and Safely
cp -r /path/to/source /path/to/backup/backup_$(date +%Y%m%d_%H%M%S) to copy files into a timestamped backup folder.Examples
How to Think About It
Algorithm
Code
#!/bin/bash SOURCE_DIR="$1" BACKUP_DIR="$HOME/backup/backup_$(date +%Y%m%d_%H%M%S)" mkdir -p "$BACKUP_DIR" cp -r "$SOURCE_DIR"/* "$BACKUP_DIR"/ echo "Backup completed to $BACKUP_DIR"
Dry Run
Let's trace backing up /home/user/docs through the script
Set source and backup paths
SOURCE_DIR="/home/user/docs" BACKUP_DIR="/home/user/backup/backup_20240601_123456"
Create backup directory
mkdir -p /home/user/backup/backup_20240601_123456
Copy files
cp -r /home/user/docs/* /home/user/backup/backup_20240601_123456/
| Step | Action | Value |
|---|---|---|
| 1 | SOURCE_DIR | /home/user/docs |
| 1 | BACKUP_DIR | /home/user/backup/backup_20240601_123456 |
| 2 | mkdir | Created backup directory |
| 3 | cp | Copied all files from source to backup |
Why This Works
Step 1: Create unique backup folder
Using $(date +%Y%m%d_%H%M%S) adds a timestamp so each backup folder is unique and old backups are not overwritten.
Step 2: Copy files recursively
The cp -r command copies all files and subfolders from the source to the backup folder, preserving the structure.
Step 3: Confirm backup completion
Printing a message with the backup path helps the user know where the files were saved.
Alternative Approaches
#!/bin/bash SOURCE_DIR="$1" BACKUP_FILE="$HOME/backup/backup_$(date +%Y%m%d_%H%M%S).tar.gz" tar -czf "$BACKUP_FILE" -C "$SOURCE_DIR" . echo "Backup archive created at $BACKUP_FILE"
#!/bin/bash SOURCE_DIR="$1" BACKUP_DIR="$HOME/backup/backup_$(date +%Y%m%d_%H%M%S)" mkdir -p "$BACKUP_DIR" rsync -av --delete "$SOURCE_DIR"/ "$BACKUP_DIR"/ echo "Backup completed with rsync to $BACKUP_DIR"
Complexity: O(n) time, O(n) space
Time Complexity
The script copies all files and folders once, so time grows linearly with the number of files (n).
Space Complexity
Backup requires space proportional to the size of the source files, so space is O(n).
Which Approach is Fastest?
Using rsync is faster for repeated backups because it copies only changed files, while cp copies everything every time.
| Approach | Time | Space | Best For |
|---|---|---|---|
| cp recursive copy | O(n) | O(n) | Simple full backups |
| tar compressed archive | O(n) | Less than O(n) | Space-saving backups |
| rsync incremental backup | O(changed files) | O(n) | Efficient repeated backups |