My goal here is to automatically launch a script when a certain USB stick is connected to the system. When plugging in the stick, the partition should be automatically mounted, a script should be executed, and some notifications should be shown on the screen.

Identifying and automounting the drive

My USB stick is a simple FAT32 drive, so to identify it I set a filesystem label. This allows me to distinguish this drive from other ones. I set the label to DOXIE.

# fatlabel /dev/sdb1 DOXIE

After some consideration of which automounting method to use, I ended up with using the built-in support for udisks2 in my file manager of choice: PCManFM. Normally, drives will only automount if I have the file manager running, but by starting it in daemon mode upon login I can get it to mount all the time.

I suspect that if you use GNOME, this would be the default behaviour anyway without having to do anything, but I had to add: pcmanfm -d & to .xinitrc to get the daemon running.

The end result is that my drive is automounted to /run/media/linus/DOXIE when plugged in.

Running script when mounted

I will use systemd to detect when a drive has been mounted. Since I’m only interested in doing this for a specific user, I will use a user service.

Create the following file ~/.config/systemd/user/doxie-import.service with the following contents.

Description=Triggers import of images from Doxie scanner



Then enable the service with

$ systemctl --user enable doxie-import

Now, this service will launch when the path /run/media/linus/DOXIE is mounted, as seen under the [Install] section. The path is escaped according to rules in systemd.unit(5). Since this is done in the context of a user session, you can use notify-send as usual within the script to present notifications to the user.