Automounting with Udev

Q I have a car PC with a USB port on the front of it, and I've loaded a slimmed down version of PCLinuxOS on to it. What I would like to do is (at init level 3) have Udev automatically mount any USB mass storage device placed into the USB port to /media/removable. I've tried writing the following rule, but it doesn't work:

SUBSYSTEMS=="usb", ATTRS{product}=="Mass Storage Device", SYMLINK:="removable",
RUN+="/bin/mount /dev/removable /media/removable"

Can you see anything wrong with this? I've read through some Udev tutorials, which have lead me to the conclusion that this should work, but /dev/removable is never created.

A The first step is to try the rule without the RUN command, to test whether it is even matching. Only when /dev/removable is being created and you can run the mount command manually should you add it to the rule. Udev is smart enough to notice changes to the rule files without a restart, so it's easy enough to keep the file in your text editor and tweak the rule while unplugging and plugging the device. When writing Udev rules, bear in mind that the attributes you match on must come from the same block of output from udevinfo. If you want to match on any USB mass storage device (which may not all have the same product attribute), try

SUBSYSTEMS=="scsi", KERNEL=="sd[a-h]1",
SYMLINK:="removable", RUN+="/bin/mount /dev/removable /media/removable"

This will mount the first partition of any USB storage device you connect. You don't need to create the /dev/removable symlink for a rule that mounts a device, though you may have other uses for this, so your rule could be simplified to

SUBSYSTEMS=="scsi", KERNEL=="sd[a-h]1",
RUN+="/bin/mount /dev/%k /media/removable"

because %k contains the kernel's name for this device, such as sda1. If your system uses the SCSI layer for hard disks, this will also match your hard disk when you boot. The solution is to explicitly exclude the hard disk from the rule. Run udevinfo to get the drive's model attribute, then add something like this to the rule:

ATTRS{model}!="superduper 500G"

Most USB mass storage devices, especially pen drives and memory cards, are set up with a single partition, so this will match on those. If you want to connect something like a USB hard drive with multiple partitions, you will need something a little cleverer, like

SUBSYSTEMS=="scsi", KERNEL=="sd[a-h][0-9]",
SYMLINK:="removable%n", RUN+="/usr/bin/pmount /dev/removable%n"

This uses pmount instead of mount, which is more sophisticated and is used by most automounters. One of its advantages is that it only needs the device node as an argument, and creates the mount point in /media automatically. Its counterpart, pumount, removes the mount point when unmounting, keeping media clean. The %n in the above rule is replaced with the kernel number, so the third partition (sda3) would be mounted at /media/removable3.

Follow us on or Twitter

Username:   Password:
Create Account | About TuxRadar