← How-Tos
raspberry-pi Mar 26, 2026 ◯ 2 min read

Auto-Backup Your Raspberry Pi SD Card to a Network Share

raspberry pibackupsd cardautomationcron

SD cards fail. Pi projects that took hours to configure vanish in an instant. Automated backups to a NAS or network share protect your work. Here's how to set it up.

Strategy

  1. Pi mounts a network share (NFS or SMB/Samba)
  2. A cron job runs a compressed backup of the Pi's own SD card
  3. Backup goes directly to the network share
  4. Old backups rotate automatically (keep last 5)

Step 1 โ€” Mount a Network Share

Samba (SMB) โ€” for NAS/Windows shares

sudo apt install cifs-utils -y
sudo mkdir /mnt/backup

Create credentials file:

sudo nano /etc/samba/user
username=your_nas_user
password=your_nas_password
sudo chmod 600 /etc/samba/user

Add to /etc/fstab:

//192.168.1.100/backups /mnt/backup cifs credentials=/etc/samba/user,iocharset=utf8 0 0

Mount:

sudo mount -a

Verify: ls /mnt/backup should show NAS contents.

Step 2 โ€” Create Backup Script

Save as /home/pi/backup.sh:

#!/bin/bash
BACKUP_DIR="/mnt/backup/pi-backups"
HOSTNAME=$(hostname)
DATE=$(date +%Y%m%d_%H%M)
FILENAME="${HOSTNAME}_${DATE}.img.gz"
KEEP=5

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Create compressed image of SD card
sudo dd if=/dev/mmcblk0 bs=4M status=progress | gzip -9 > "$BACKUP_DIR/$FILENAME"

# Rotate โ€” keep only last N backups
cd "$BACKUP_DIR"
ls -t ${HOSTNAME}_*.img.gz | tail -n +$((KEEP+1)) | xargs -r rm --

echo "Backup complete: $FILENAME"

Make executable:

chmod +x /home/pi/backup.sh

Step 3 โ€” Schedule with Cron

sudo crontab -e

Add (runs every Sunday at 2am):

0 2 * * 0 /home/pi/backup.sh >> /home/pi/backup.log 2>&1

Restore from Backup

On another computer:

# Decompress and write to new SD card
gunzip -c pi-backup.img.gz | sudo dd of=/dev/sdX bs=4M status=progress

Replace /dev/sdX with your SD card device.

Smaller Backups with pishrink

pishrink shrinks the image to actual used space (not full SD card size):

wget https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh
chmod +x pishrink.sh
sudo ./pishrink.sh backup.img

Tips

TipDetail
Pi 4 SD cardFull 32GB card โ‰ˆ 8โ€“10GB compressed
Backup windowDo at off-hours โ€” backup slows Pi significantly
Test restoreRestore to a spare SD card every few months to verify
rsync alternativeFor partial backups of /home/pi only โ€” much faster