Bash Script to Schedule Backup with Cron Job
crontab -e by adding a line like 0 2 * * * /path/to/backup.sh to run daily at 2 AM.Examples
How to Think About It
crontab -e to run your script automatically at the times you choose.Algorithm
Code
#!/bin/bash # backup.sh - simple backup script SOURCE_DIR="$HOME/documents" BACKUP_DIR="$HOME/backup/documents" mkdir -p "$BACKUP_DIR" cp -r "$SOURCE_DIR"/* "$BACKUP_DIR" echo "Backup completed at $(date)"
Dry Run
Let's trace backing up /home/user/documents to /home/user/backup/documents
Create backup directory
mkdir -p /home/user/backup/documents creates the folder if missing
Copy files
cp -r /home/user/documents/* /home/user/backup/documents copies all files
Print confirmation
echo prints 'Backup completed at [current date]'
| Step | Command | Effect |
|---|---|---|
| 1 | mkdir -p /home/user/backup/documents | Creates backup folder if not exists |
| 2 | cp -r /home/user/documents/* /home/user/backup/documents | Copies all files from source to backup |
| 3 | echo Backup completed at ... | Prints completion message with timestamp |
Why This Works
Step 1: Backup script copies files
The script uses cp -r to copy all files recursively from the source to the backup folder.
Step 2: Scheduling with cron
Cron runs the script automatically at the scheduled time using the crontab entry.
Step 3: Automated backups
This setup ensures backups happen regularly without manual intervention.
Alternative Approaches
#!/bin/bash SOURCE_DIR="$HOME/documents" BACKUP_FILE="$HOME/backup/documents_$(date +%Y%m%d).tar.gz" mkdir -p "$HOME/backup" tar -czf "$BACKUP_FILE" -C "$SOURCE_DIR" . echo "Backup archive created at $BACKUP_FILE"
#!/bin/bash SOURCE_DIR="$HOME/documents/" BACKUP_DIR="$HOME/backup/documents/" mkdir -p "$BACKUP_DIR" rsync -av --delete "$SOURCE_DIR" "$BACKUP_DIR" echo "Incremental backup completed at $(date)"
Complexity: O(n) time, O(n) space
Time Complexity
The backup time depends on the number of files and their sizes (n). Copying or archiving all files takes linear time.
Space Complexity
Backup requires additional space equal to the size of the files being copied or archived.
Which Approach is Fastest?
Using rsync is faster for repeated backups because it copies only changed files, reducing time and space usage.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple cp script | O(n) | O(n) | Small backups, simplicity |
| Tar archive | O(n) | O(n) | Compressed backups, archiving |
| Rsync incremental | O(k) where k ≤ n | O(k) | Frequent backups, efficiency |