Version 0 of USB FAT Semi-Auto-Mount

Updated 2009-01-28 13:53:49 by peterc


This is one of those little scripts you write to make life a bit more convenient. It somewhat replicates the behaviour of the Mac OS X automounter where your USB disks simply appear on your desktop when you plug them in. I use it to get similar behaviour on my Linux box. The only real difference is here we run it manually, instead of waiting for it to trigger whenever the OS feels like it, and it cleans up after itself promptly.

The script

 # By peterc
 set mountdirroot "/multimedia"
 set userid pc
 set groupid users

 proc get_mounted {} {
  set tmp [split [exec /bin/mount] "\n"]
  set ::mountdevices [list]
  set ::mountpoints  [list]
  foreach t $tmp { lappend ::mountdevices [lindex [split $t " "] 0] }
  foreach t $tmp { lappend ::mountpoints [lindex [split $t " "] 2] }


 # Mount any devices present
 set pause 0
 foreach device { sda1 sda2 sda3 sda4 sdb1 sdb2 sdb3 sdb4 sdc1 sdc2 sdc3 sdc4 sdd1 sdd2 sdd3 sdd4 sde1 sde2 sde3 sde4 sdf1 sdf2 sdf3 sdf4 } {
  if {[catch { exec /usr/bin/mlabel -i /dev/$device -s :: } tmp ]} { continue }
  set devlabel [lindex $tmp 3]
  puts -nonewline "Found $::mountdirroot/$devlabel at /dev/$device "
  if {[lsearch -exact $mountdevices /dev/$device] > -1} {
   puts "and it is already mounted."
   } else {
   puts "and will mount it now."
  catch { file mkdir /multimedia/$devlabel } ;# We don't really care if it already exists.
  exec mount -o rw,noexec,nodev,sync,noatime,uid=$userid,gid=$groupid,shortname=mixed /dev/$device $mountdirroot/$devlabel


 # Remove any directories present where nothing is mounted.
 set mountdirs [glob -tails -directory $::mountdirroot *]
 foreach d $mountdirs {
  if {[lsearch -exact $mountpoints $mountdirroot/$d] < 0} {
   puts -nonewline "Found surplus mount point $d and will remove it: "
   if {[catch {file delete $mountdirroot/$d} err]} { puts "$err" } else { puts "done." }
   set ::did(rm) 1
   } else {
   # puts "Mount point $d is being used. Will leave that alone."
 if {![info exists ::did(rm)]} { puts "No surplus mount points found." }

Config and other things of note

The main configurables are mountdirroot (in this case, /multimedia), userid and groupid (username and group you want given to the mounts).

Unlabelled disks and disks with spaces will probably cause this script grief but not really cause anything serious to happen. Use underscores and dashes in your disk labels.

This automount script only supports the various FAT systems that mtools does. That includes FAT up to FAT32. Other filesystems won't be recognised and won't be mounted.

Double-check what devices your harddrives are and remove them from the devices list if they conflict. Better safe than sorry, eh. If you're really keen, I guess you could populate this list by running a glob on your /dev tree, but, I've never had a USB use any device not in that list (so far!).

Spot for comments and questions