1

Basically, I have a small file that I'd like to back up onto various storage devices. Is there any way to make that happen automatically whenever a new drive is mounted (be it a hard disk on boot, or a flash drive while the system is already running)? Probably not the most efficient thing in the world, but it'd be cool if I could just plug a drive in and have another copy of the file without having to think about it.

1

Using RUN+= is the wrong approach. As man udev makes clear:

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.

The correct approach is using SYSTEMD_WANTS (from man systemd.device):

THE UDEV DATABASE The settings of device units may either be configured via unit files, or directly from the udev database (which is recommended). The following udev properties are understood by systemd:

SYSTEMD_WANTS= Adds dependencies of type Wants from this unit to all listed units. This may be used to activate arbitrary units, when a specific device becomes available. Note that this and the other tags are not taken into account unless the device is tagged with the "systemd" string in the udev database, because otherwise the device is not exposed as systemd unit.

You just need a service file in /etc/systemd/system/media-USBDRIVE.mount.wants/:

[Unit]
Description=Backup files to USBDRIVE
Requires=media-USBDRIVE.mount
After=media-USBDRIVE.mount

[Service]
ExecStart=/path/to/backupscript

[Install]
WantedBy=media-USBDRIVE.mount

Note: this assumes your USB drive is called USBDRIVE and is mounted at /media/USBDRIVE.

0

If you are using systemd then the person here has already answered this.

To place a rule

KERNEL=="sd?1",ACTION=="mount",RUN+="/path/to/script.sh"

in

/etc/udev/rules.d/

Note the caveat re execution as root, put whatever action you need doing in your script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.