When a new device appears, udev is notified. It normally creates a device file under /dev
based on built-in rules¹. You can override these rules to change the device file location or run an arbitrary program. Here is a sample such udev rule:
KERNEL=="sd*", ATTRS{vendor}=="Yoyodine", ATTRS{serial}=="123456789", NAME="keepass/s%n", RUN+="/usr/local/sbin/keepass-drive-inserted /dev/%k%n"
The NAME=
directive changes the location of the device file, I included it for illustration purposes but it is probably not useful for your use case. The ATTRS
rules identify the device; run udevinfo -a -n /dev/sdz
when the drive is available as /dev/sdz
to see what attributes it has. Beware that you can only use ATTRS
rules from a single section of the udevinfo
input (in addition, you can use ATTR
rules from the initial section). See Understand output of `udevadm info -a -n /dev/sdb` for more background. This rule goes into a file called something like /etc/udev/rules.d/local-storage-keypass.rules
.
Put the commands you want to run in the script given in the RUN
directive. Something like:
#!/bin/sh
set -e
if [ -d /media/keypass-drive ]; then
[ "$(df -P /media/keypass-drive | awk 'NR==2 {print $1}')" = "$(df -P /media | awk 'NR==2 {print $1}')" ]
else
mkdir /media/keypass-drive
fi
mount "$1" /media/keypass-drive
su ereon -c 'keypass2' &
If you're having trouble running a GUI program from a script triggered from udev, see Can I launch a graphical program on another user's desktop as root?
¹ Not on modern systems where /dev
is on udevtmpfs.
udevadm info -a -n /dev/sdX
, you cannot match based on multiple ancestors. You can only match based on data from the device itself, and a single ancestor. This is covered inman 7 udev
, but is a small comment easily overlooked. – phemmer Nov 06 '13 at 04:09