How to run a script when a specific flash-drive is mounted?

Is there a way to run a script when a particular USB device is mounted?

I keep my videos on a separate USB and would like to run a script that would mount the video folder on the USB device to the one in the home folder.


There's much nicer solution with systemd now. You create a service which depends and is wanted by you media e.g.: /etc/systemd/system/your.service

[Unit]
Description=My flashdrive script trigger
Requires=media-YourMediaLabel.mount
After=media-YourMediaLabel.mount

[Service]
ExecStart=/home/you/bin/triggerScript.sh

[Install]
WantedBy=media-YourMediaLabel.mount

Then you have to start/enable the service:

sudo systemctl start your.service
sudo systemctl enable your.service

After mount, systemd fires your trigger script. The advantage over udev rule is that the script really fires after mount, not after adding system device.

Use case: I have an encrypted partition which I want to backup automatically. After adding the device I have to type in the password. If I hooked the backup script to udev, the script attempts to run at the time when I'm typing password, which will fail.

Resource: Scripting with udev

Note: You can find your device unit with:

systemctl list-units -t mount

Start by finding your device in lsusb. Note the ID (eg 0a81:0101)

Create a new udev rules file in /etc/udev/rules.d/ via sudoedit /etc/udev/rules.d/100-mount-videos.rulesand plonk a new rule in there like this:

ACTION=="add", ATTRS{idVendor}=="0a81", ATTRS{idProduct}=="0101", RUN+="/home/your_username/bin/mount_videos.sh"

Note how I used the ID from lsusb.

Then you just need to write the script to do the work. A simple mount command should work. You might need a sleep 5 command in there to wait for the filesystem to initialize (if you leave gnome to do the main mounting -- but you're free to mount it first and then you might not need the sleep).

Addition from Allan: Long running scripts might block "all further events for this or a dependent device". My Mint man page further states "Long running tasks need to be immediately detached from the event process itself." No tip is given on where to gain the skill to do this.

Reply from Oli: Wrap it like so: https://askubuntu.com/a/106359/449