Skip to main content
4 of 4
added 109 characters in body

Run backup script after systemd automounts specific USB device

I need to run a script after a specific USB stick is mounted, particulary, to perform a backup.

I've seen many (and old) posts that mount devices inside udev rules, however modern OSes already have systemd preconfigured to automount flash drives.

I have this udev rule,

ACTION=="add", ATTRS{idVendor}=="1234", ATTRS{idProduct}=="000c", SUBSYSTEM=="block", ENV{ID_FS_USAGE}=="filesystem", RUN+="/home/me/scripts/backup-x.sh" 

as that's the only Linux kernel hook I know where I can specifically run something after device is connected.

However, as device gets automounted by systemd ie. at /media/me/0021-0000 right after connected:

Sep 27 12:32:00 t14 udisksd[1272]: Mounted /dev/sda at /media/me/0021-0000 on behalf of uid 1000 

I guess I shouldn't mount it before (and even perform a long operation, like a backup) inside a udev RUN script. Tried this inside the RUN script,

systemd-mount --owner me $DEVNAME /mnt/x zip /home/me/x/backup-$(date +'%Y-%m-%d_%H%M%S').zip /mnt/x/* 

however, it results in 2 different mounts. Mine happening first, and then the auto /media/me/0021-0000. I wonder if that's fine or not.

What's the simplest and correct approach to achieve it?

PD: running Pop!_OS 22.04LTS