Automounting – How to Automatically Mount Removable Media in /media/

automountingmount

I have a Debian sid system (Wheezy) (and same for arch), without any desktop environment (and no Xorg at all).

I can mount my SD-cards, USB sticks, external HDD by label into a specified directory in /media/ manually with mount / umount and the suitable entries in /etc/fstab, or automatically at boot time, but this is compelling, to restrictive and not dynamic enough for my needs: if I want them to be mounted in /media/<LABEL>, each device with a different <LABEL> needs its own entry, and each <LABEL> subdirectory needs to be created / removed manually in /media/ as well).

So, what is the best way to mount them automatically in /media/<LABEL> at insertion (and to unmount them from the filesystem as soon as they are unplugged no matter how risky it is for the data)?

The ideal solution would:

  1. detect when a removable media is plugged-in (i.e. when added in /dev/ as
    sdax, sdbx, … by udev)
  2. create a directory in /media/ according to its label (label of the removable media)
  3. mount it in the directory /media/<LABEL> in RW mode (if it's filesystem supports that) with flush option (for a vfat)
  4. detect if the media has been unplugged
  5. if then, unmount it from the filesystem
  6. remove the corresponding directory from /media/

(the devices should be mounted in synchronous mode oviously, to avoid any data loss when hot unplugged because of caching edit: sync is way too much for vfat removable media so flush has been created as a compromise, less secure than sync, but less risky according to the life-cycles of flash memories)

I found some info about autofs, HAL, udisks, udisks2, usbmount etc., but it's unclear which one is deprecated or preferred, and anyway, I haven't figured out how to configure them easily on my system to do that, up to now …

Best Answer

I think you're looking for pmount.

If you want automatic mounting upon insertion, see Automounting USB sticks on Debian.

If your system uses udisks2, that's the preferred way of reacting to the insertion of a removable storage device. See the Arch Wiki for configuration tips for Udisks.

Otherwise, the program that reacts when a new device appears is udev, so automatic mounting is triggered by a udev rule. The usbmount package provides udev rules to automatically mount USB storage devices and a few others. Calling mount from udev rules doesn't work for FUSE filesystems (such as ntfs-3g), so use udisks if you need that.

You cannot automatically unmount media when they are removed because causality doesn't work that way. The media must be unmounted before it is removed. For read-only media, you can get away with unmounting after removal, although this might confuse some applications if they have files open on the suddenly-vanished filesystem. For writable media, if you unplug a mounted filesystem, data corruption is likely.

Related Question