Pi-Backup automation

My Raspberry Pi runs many small applications, and twice the microSD card stopped working. So I automated a weekly backup to my NAS.

1. Mount the NAS

Create the folder /mnt/backup, then edit /etc/fstab:

sudo nano /etc/fstab

Add a line like this (adjust to your NAS path and credentials file):

//192.168.100.2/folder/on-your-nas /mnt/backup cifs iocharset=utf8,uid=1001,gid=1001,x-systemd.automount,x-systemd.requires=network-online.target,vers=1.0,credentials=/home/user/.ds414-pi-backup.creds

Create the credentials file:

nano ~/.ds414-pi-backup.creds

Content:

username=myNASUSER
password=myPassword

Set strict permissions on the credentials file so other users can't read it. Apply the fstab:

sudo mount -a

Test the share and reboot to verify the automount works.

2. Download the backup script

Use bkup_rpimage — based on the Raspberry Pi backup thread.

Place it in /mnt/backup and make it executable:

chmod +x /mnt/backup/bkup_rpimage.sh

Test run:

sudo ./bkup_rpimage.sh start -L backup-$(date +%Y-%m-%d).log -czd /mnt/backup/$(uname -n)-$(date +%Y-%m-%d).img

3. Create a wrapper script

nano /mnt/backup/backup_pi.sh
#!/bin/bash
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
. /mnt/backup/bkup_rpimage.sh start -czdl /mnt/backup/$(uname -n)-$(date +%Y-%m-%d).img
chmod +x /mnt/backup/backup_pi.sh

This creates a gzipped backup image and removes the uncompressed version when done. Adjust PATH to match your environment (echo $PATH). The script runs as root via cron, so the root PATH applies.

4. Automate with cron

sudo crontab -e

Add at the end:

0 3 * * 1 /mnt/backup/backup_pi.sh

Runs every Monday at 3 AM. To test, temporarily change to * * * * *.

Useful commands

Check running cron jobs:

ps fauxww | grep -A 1 '[C]RON'

View syslog for cron output:

sudo tail /var/log/syslog

Restore

Use Raspberry Pi Imager, select "custom image", and pick the unzipped .gz file.