2

I want to copy a directory and its contents to my external USB hard drive when I connect it to my laptop automatically.

So, I created a file called 00-usb-backup.rules on /etc/udev/rules.d with this content:

ACTION=="add", ATTRS{idVendor}=="0480", ATTRS{idProduct}=="a208", RUN+="/home/fabio/bin/backup"

The backup script has permission to run as a program. And its content is:

#! /bin/bash
cp -r /home/fabio/Ads/ /media/fabio/BACKUP/teste/

Following the answer on another thread, I edited visudo and added the following on the last line:

fabio ALL=(ALL) NOPASSWD: /home/fabio/bin/backup

But when I connect the USB hard drive nothing happens. :(

Any ideas on what could be wrong?

Thanks!

Liso
  • 15,677
FabioB
  • 63

2 Answers2

2

Execute script when usb drive are plugged in.

RUN{type}:
This can only be used for very short-running foreground tasks. Running an event process for a long period of time may block all further events for this or a dependent device. Starting daemons or other long-running processes is not appropriate for udev; the forked processes, detached or not, will be unconditionally killed after the event handling has finished. Note that running programs that access the network or mount/unmount filesystems is not allowed inside of udev rules, due to the default sandbox that is enforced on systemd-udevd.service.

/etc/udev/rules.d/90-usb-backup.rules:

ACTION=="add", SUBSYSTEM=="block", \
ATTRS{idVendor}=="0480", ATTRS{idProduct}=="a208", \
ENV{DEVTYPE}=="partition", RUN+="/bin/sh -c '/home/fabio/bin/backup.sh'"

/home/fabio/bin/backup.sh:
(make sure your script has execution bit set; chmod +x script)

#!bin/bash

if [[ -b $DEVNAME ]] && \
   mount $DEVNAME /home/fabio/Ads/
then
   cp -a /home/fabio/Ads/ /media/fabio/BACKUP/teste/
fi

this will not mount the drive on the system, just inside the sandbox.

0

This is what I do: a systemd service (e.g. borgmatic.service) is triggered by a udev rule based on the hot plug event.

SUBSYSTEM=="block", ACTION=="add", ENV{DEVTYPE}=="partition", TAG+="systemd", ENV{SYSTEMD_USER_WANTS}="borgmatic.service"

For the service in my ~/.config/systemd/user folder

[Unit] Description=/home backup

[Service]

Type=oneshot

ExecStart=/home/xxx/.local/bin/borgmatic