Rsync a USB drive / SD card on mount in Unraid
Nov 2023edit on 04/12: It has come to my attention that the Disk Devices plugin allows you to define scripts that will run when a given drive is attached. This seems to be a better way to do things — I will update this post shortly!
I use Unraid to store and manage all of my media, including photos taken on various devices.
I wanted to be able to plug in a drive or card and have it automatically sync in to a predefined directory on my server, delete the synced files from the drive, and then unmount the drive.
This can be achieved with rsync and a udev rule. This should actually work on any Linux distro, but some steps below are specific to Unraid.
To do this with Unraid, you will firstly need the Unassigned Devices plugin. This allows you to manage storage devices connected to your server that are not part of your array. If you want to work with HFS+, exFAT or apfs-formatted drives, you will also need the Unassigned Devices Plus plugin (more info at the same link above).
Once you've installed the plugins, you will see the devices under Disk Devices
in the Main tab. Click the cog settings icon next to the drive you want to rsync, and make sure Automount
is turned on.
Now we will set up the udev rule, which will tell the OS to run a script every time a drive is plugged in.
Create a file called sync_and_eject.sh
somewhere (I put it in /mnt/user/scripts
)
#!/bin/bash
# Set your source and destination paths
SOURCE="/mnt/disks/YOUR_DRIVE"
DESTINATION="/mnt/user/backup"
# Run rsync to sync the data
rsync -av --remove-source-files "$SOURCE/" "$DESTINATION/"
# Eject the USB drive
umount "$SOURCE"
Make sure to update SOURCE
and DESTINATION
to the location of your device and the place your want to sync it to.
You'll also need to make the script executable -
chmod +x sync_and_eject.sh
Before you run this, you should make sure the script is behaving as you expect. Run it with the --dry-run
flag first.
Create a new file at /etc/udev/rules.d/99-custom.rules
(the filename doesn't really matter):
SUBSYSTEMS=="usb", KERNEL=="sd*[!0-9]", ACTION=="add", RUN+="/path/to/sync_and_eject.sh"
Make sure to update the path/to/sync_and_eject.sh to the path of your script.
Reload the rules:
udevadm control --reload-rules
Now the next time you plug in your device, the udev rule will run your script. This will rsync the files to your server, delete them from the device, and eject the device.