You ever wanted your Linux machine make automatically backup if a USB harddrive is attached? On systemd based distros this works best this way (example is from opensuse):

  • Create file /etc/systemd/system/backup@.service with content:
[Unit]
Description=Backup to USB Disk
BindsTo=dev-%i.device

[Service]
Type=simple
ExecStart=/usr/local/bin/backupUSB.sh %I


The meaning of %i and %I is explained in systemd.unit man page. These are the "instance names". The BindsTo line causes the service to be stopped on device detach.

  • Reload systemd:
systemctl daemon-reload


  • Create a udev rule in file /etc/udev/rules.d/99-backup.rules:
KERNEL=="sd?1", ACTION=="add", SUBSYSTEMS=="scsi", ATTRS{vendor}=="TOSHIBA", ATTRS{model}=="External USB 3.0", RUN+="/usr/bin/systemctl --no-block start backup@%k.service"


or you want to use data from the usb subsystem:

KERNEL=="sd?1", ACTION=="add", SUBSYSTEMS=="usb", ATTRS{manufacturer}=="Toshiba", ATTRS{product}=="External USB 3.0", ATTRS{serial}=="2013XXXXXXXXXC", RUN+="/usr/bin/systemctl --no-block start backup@%k.service"


You probably want to change vendor, model and for sure serial parameters. You can find the parameters if the device is attached by calling (example: the device is sdg):
udevadm info --attribute-walk --path=/sys/block/sdg


More info in the udev man page. %k is the "kernel name" -> for example "sdb1".

  • Reload udev rules:
udevadm control --reload


  • Create a script that makes the backup at /usr/local/bin/backupUSB.sh.

The script will get the device path as parameter ($1).

Example:
#!/bin/bash

PATH=$PATH:/sbin:/usr/sbin
export PATH

USBDISK="/dev/$1"

# where to mount

MOUNTHERE=/backup_toshiba1t

# ionice
ionice -n 7 -p $$

if [ ! -e $USBDISK ] ; then
  echo "Device $USBDISK not avalible. Exiting"
  exit 1
fi


# Try to umount

umount $MOUNTHERE

# Try to mount

mkdir -p $MOUNTHERE
mount $USBDISK $MOUNTHERE
if [ $? != 0 ] ; then
  echo `basename $0`": unable to mount $USBDISK on $MOUNTHERE. Exiting."
  exit 1
fi


echo "Disk space before backup:"
df -h $MOUNTHERE

echo "backup (rsnapshot) starting"
rsnapshot -c /etc/rsnapshot_toshiba1t.conf daily
echo "backup done"

echo "Disk space after backup:"
df -h $MOUNTHERE

umount $USBDISK



Taken from here: https://forums.opensuse.org/showthread.php/485261-Script-run-from-udev-rule-gets-killed-shortly-after-start