IgnorantGuru's Blog

Linux software, news, and tips

Script: devmon

«Downloads

Download Links: devmon is now distributed as part of udevil.
Follow the udevil installation instructions which will also install devmon. You can also just download the devmon script by itself (right-click and Save Link As).
Description: Automounts and unmounts optical and removable drives
Recommended For: Linux
Requires: udevil* bash>=4
Recommended: eject zenity
*Optional: udisks v1 may be substituted for udevil. If udevil is not set suid, udisks v1/v2 or pmount is required (see table)
License: GNU GPL v3
Related: udevil spacefm mountiso autofatsort
News: What’s New In udevil & devmon?
Feedback: commentsissues

 
UPDATE: devmon is now distributed as part of udevil. If you installed devmon from a package, remove it to install a udevil package which includes the latest devmon.

UPDATE: The new SpaceFM file manager includes much of the functionality of devmon built-in.
 

Jump To Installation Instructions
 

Overview


devmon is a configuration-less bash daemon script which automounts optical discs and removable drives. It can also selectively autostart apps or execute commands after mounting, ignore specified devices and volume labels, and manually mount and unmount devices.

devmon 1.1.0 and later is distributed with and uses udevil for device monitoring and mounting, removing all dependencies on udisks, policykit, consolekit, gvfs, etc. devmon can also be used with udisks v1, or some combinations of udevil, udisks v2, and pmount (see table).

 

devmon --help

devmon version 1.1.9  (distributed with udevil)
Automounts and unmounts optical and removable drives
Requires:    udevil bash>=4        Also Recommended: eject spacefm|zenity
Optional:    udisks v1 may be substituted for udevil
             If udevil is not set suid, udisks v1/v2 or pmount is required
Usage: devmon [AUTOMOUNT-OPTIONS]  # Run as daemon to automount
       devmon [MOUNT-OPTIONS]      # Or run as client to manually un/mount
AUTOMOUNT-OPTIONS:  (these can be used only in daemon mode)
--exec-on-device DEVICE "COMMAND"  Execute COMMAND after mounting DEVICE
--exec-on-label "LABEL" "COMMAND"  Execute COMMAND after mounting LABEL
--exec-on-video "COMMAND"          Execute COMMAND after video DVD mount
--exec-on-audio "COMMAND"          Execute COMMAND after audio CD insertion
--exec-on-disc  "COMMAND"          Execute COMMAND after data CD/DVD mount
--exec-on-drive "COMMAND"          Execute COMMAND after drive mount
--exec-on-unmount "COMMAND"        Execute COMMAND after unmount
--exec-on-remove  "COMMAND"        Execute COMMAND after drive removal
  Where the following in COMMAND will be replaced with:
     %d    mount point directory (eg /media/cd)
     %f    device name (eg /dev/sdd1)
     %l    label of mounted volume
  Multiple --exec-on-XXX options may be used to execute multiple commands.
  Other exec-on-XXX commands are ignored if exec-on-device or -label executed.
--mount-options "OPTIONS"          Default: noexec,nosuid,nodev,noatime
--info-on-mount                    Show mounted drive info in a popup dialog
--no-mount                         Don't mount anything, just exec (disables
                                   --exec-on-video)
--no-unmount                       Don't unmount all removable drives on exit

MOUNT-OPTIONS:  (these can be used only in client mode)
--unmount-removable | -r      Sync and unmount all removable drives and show
                              pop-up dialog (spacefm or zenity required)
--unmount-recent | -c         Unmount most recently mounted removable drive
--unmount-optical | -o        Unmount all optical drives (error pop-up only)
--unmount-all | -u            Same as --unmount-removable --unmount-optical
--unmount DIR|DEVICE          Unmount DEVICE or mount point DIR
--eject DIR|DEVICE            Unmount and eject DEVICE or mount point DIR
--mount-all | -a              Mount all removable and optical drives
--mount DEVICE                Mount DEVICE
--mount-options|--mount-fstype|--eject-options "OPTIONS"
                              These options will be passed to mount or eject
--enumerate-device-files      List known devices

UNIVERSAL OPTIONS:  (these can be used in both daemon and client modes)
--ignore-device DEVICE        Ignore DEVICE (eg /dev/sdd1)
--ignore-label "LABEL"        Ignore volume with LABEL
--sync | -s                   Add sync mount option for ext2-4 ntfs ufs, or
                              flush for fat & vfat (slower writing but safer)
--internal                    Also attempt to un/mount internal system drives
                              (this is mostly a fix for esata issues)
--always-exec                 Also run --exec-on-XXX commands during startup or
                              with --mount-all
--no-gui | -g                 Do not show spacefm/zenity pop-up dialogs

 

Automounting (Daemon Mode)

In daemon mode, devmon runs continuously to monitor drive changes, automount filesystems, and autostart apps.

To experiment with what devmon options work best for you, first open a terminal window and run:

devmon

Leave devmon running in that window and it will output debug messages as devices are inserted and removed.

To start devmon and leave it running in the background use:

devmon &

While devmon is running, any optical discs or removable drives should be silently and automatically mounted in /media. (For esata drives see Known Issues.)

To stop devmon, press Ctrl-C, or if it was backgrounded, open another console window and run:

killall devmon udisks

(Be careful that multiple instances of devmon aren’t running in the background or it can produce confusing results.)

 
You can also experiment with various ––exec-on-XXX options to automatically start programs after devices are mounted. For example, to have devmon open newly mounted removable drives with the SpaceFM file manager:

devmon --exec-on-drive "spacefm %d"

Another example: To have devmon open removable drives and data CDs/DVDs with the file manager, and open video DVDs and audio CDs with vlc:

devmon --exec-on-drive "spacefm %d"                     \
       --exec-on-disc  "spacefm %d"                     \
       --exec-on-video "vlc --verbose=-1 dvd://%f"             \
       --exec-on-audio "vlc --verbose=-1 cdda://%f"

The exec-on-XXX command(s) specified will be executed after a drive is auto-mounted. %d, if present in the command, will be replaced with the mount point (eg /media/cd), %f will be replaced with the device (eg /dev/sdd1), and %l with the volume label. Multiple exec-on-XXX options may be specified to issue multiple commands. For example:

devmon --exec-on-drive "spacefm %d"                     \
       --exec-on-drive "echo %f mounted on %d >> /tmp/automount.log"

 
Commands are executed in order, but asynchronously (in parallel, such that the second command may execute before the first has finished). To run commands synchronously, use a script or consider using this form:

devmon --exec-on-drive "command1 ; command2"

 
If an exec-on-device or exec-on-label option causes commands to be executed, other exec-on-XXX commands will not be executed. For example, exec-on-device can be used to call a custom script anytime that media is inserted. exec-on-label can be used to perform a custom action when a particular volume label is mounted, overriding the default commands for that volume type.

 
exec-on-unmount and exec-on-remove commands are executed when a device is unmounted or removed. (Note that exec-on-unmount may not execute for devices mounted before devmon was started.) For one example, see a user-contributed script which adds device icons to your desktop. Another example: to have devmon automatically add and remove drives from traydevice you might use:

devmon --exec-on-drive  "traydevice %f" \
       --exec-on-remove "pkill -f \"traydevice %f\""

 
Note that commands are executed with eval. This means that some special characters may need to be escaped (place a slash \ in front of the character). Also note that the contents of %d and %l are passed by devmon in single quotes, so using single quotes around them may not work. For best results use escaped double quotes. For example, to execute this command containing quotes (which uses notify-send to alert you of new drive mounts):

notify-send --icon=block-device --urgency=low "Volume %l has been mounted"

you would use (escaped quotes shown in red):

devmon --exec-on-drive "notify-send --icon=block-device --urgency=low \"Volume %l has been mounted\""

 
The ––no-mount option inhibits all mounting, but exec-on-XXX commands are still executed when a device is inserted. This allows you to handle the mounting conditionally using your own scripts or commands.

On initial startup, devmon will mount optical discs and removable drives if present and unmounted, but will not execute commands (unless the ––always-exec option is included). This means that if you have a CD in the drive or a removable drive inserted when you login, they will be mounted.

On exit (normally only when you log out of your session), devmon will attempt to unmount all removable drives, which prevents mount directories being left behind in /media. If you don’t want devmon to unmount all removable drives on exit, use the ––no-unmount option.

To help prevent data loss, you can specify the ––sync option, which causes ext2, ext3, ext4, and ufs filesystems to be mounted with the ‘sync’ option, and fat and vfat filesystems to be mounted with the ‘flush’ option (flush requires a 2.6.19 or later kernel). This may reduce the speed of writing to the drive, but will make it less likely data will be lost if the drive is removed without being unmounted first. In any case, you should manually unmount drives before removing them (see below).

Once you have devmon working as you like, follow the installation instructions to start devmon automatically when you login.

 

Manual Mounting And Unmounting (Client Mode)

While one instance of devmon may be running in automounting daemon mode (or not), as described above, another instance of devmon can be run to mount or unmount devices. For example, it is handy to associate this command with a keyboard shortcut, which will unmount all removable drives making them safe to remove:

devmon --unmount-removable

If zenity is installed on the system, a pop-up dialog will report what removable devices are being unmounted. This dialog will close automatically when unmounting is complete – it is then safe to remove the devices. (Note: Pressing OK on the dialog will close the dialog prematurely but will not stop the unmounting process.) If an unmounting error occurs, a pop-up dialog will announce it. (If the error reports the filesystem is busy, try closing all programs which used that filesystem.)

Other examples of manual devmon mounting and unmounting:

# Unmount all removable and optical drives:
devmon --unmount-all

# Unmount and remount all removable drives:
devmon -ra    # same as --unmount-removable --mount-all

# Unmount the optical drive by device name, and a usbstick by mount point:
devmon --unmount /dev/sr0 --unmount /media/usbstick

 

Installation Instructions

Install devmon and Dependencies

The easiest way to install devmon is to install udevil, using either the Debian/Ubuntu PPA, another distro package, the self-installer, or the build instructions in the README.

Alternatively, you can download just the devmon script alone and follow the standard Script Installation Instructions like this:

wget https://raw.github.com/IgnorantGuru/udevil/master/src/devmon
sudo install devmon /usr/local/bin/devmon

devmon also requires bash version 4 or higher, and recommends eject and zenity. For example, on Debian/Ubuntu:

apt-get install eject zenity

 

Install udevil or udisks v1

devmon can be used with just udevil, or with some combinations of udisks and pmount, as detailed in the table below:

    devmon With Recommends
    any version udisks1 zenity
    1.1.0 and later udevil (set suid) eject zenity
    enable polling
    1.1.0 and later udevil + udisks1 eject zenity
    1.1.0 and later udevil + udisks2 eject zenity
    enable polling
    1.1.0 and later udevil + pmount eject zenity
    enable polling

udevil or udisks v1 is required for devmon’s device monitoring. devmon cannot be used with only udisks v2 or pmount alone. For devmon mounting, udevil does not need to be run suid if pmount, udisks v1, or udisks v2 is installed.

If devmon can’t find what it needs, it will display a warning at startup.

Especially if using devmon without udisks, remember to enable kernel polling(this is now already done with most distros).

 

Stop Other Automounters

If you have other automounting scripts, programs, or udev rules installed, be sure to remove or disable their automounting features, or they may interfere with devmon or create confusing behavior.

 

Start devmon Automatically (mounting via udevil suid or pmount)

If using devmon with udevil set suid, devmon can be started anywhere you like. devmon should be run as a normal user (not root usually). It’s usually easiest to start it in your window manager’s startup script or other post-login autostart method. For example, if you use Openbox, launch devmon in autostart.sh:

( sleep 5 && devmon [OPTIONS] ) &

where [OPTIONS] should be replaced with any desired options.

 
If you use Ubuntu, see this post for basic startup instructions. (Note: ‘devmon’ is no longer in the PPA – use the ‘udevil’ package instead.)

 
If you want to log devmon’s output for troubleshooting purposes, redirect its output like this:

devmon &>/tmp/devmon.log

The file /tmp/devmon.log will be appended as devices are added, mounted, and removed.

The rest of the installation instructions below only apply if you’re using devmon with udisks.

 

Start devmon Automatically (mounting via udisks)

If udevil is not installed or is not set suid, and udisks is installed, then devmon will use udisks to mount devices. If using udisks for mounting, these instructions apply to you. Otherwise just follow the instructions above.

udisks requires permission for the org.freedesktop.udisks.filesystem-mount action to be granted through PolicyKit, which usually requires running a ConsoleKit session. If your login manager has native ConsoleKit support (most do), this may be taken care of automatically. devmon must be run within the consolekit session for udisks to be properly authorized.

If your login manager does not have native ConsoleKit support, you may need to explicitly start your window manager with ConsoleKit. For example, to start Openbox with ConsoleKit, change the “exec openbox-session” line in your ~/.xinitrc file to:

exec ck-launch-session openbox-session

 
It is best to set devmon to start after your window manager session has started using your window manager’s initialization script or other post-login autostart method. For example, if you use Openbox, launch devmon in autostart.sh:

( sleep 5 && devmon [OPTIONS] ) &

where [OPTIONS] should be replaced with any desired options.

 
If you need to start devmon in ~/.xinitrc, you can try this method:

exec ck-launch-session bash -c "devmon [OPTIONS] & openbox-session"

 
If you use Ubuntu, see this post for basic startup instructions.

 
If you want to log devmon’s output for troubleshooting purposes, redirect its output like this:

devmon &>/tmp/devmon.log

The file /tmp/devmon.log will be appended as devices are added, mounted, and removed. If the first line of this file reads “Poll for media failed: Not Authorized”, then udisks is not getting the required permissions through a ConsoleKit session, and devmon may not be able to mount devices (see Troubleshooting below).

 

Testing UDisks v1

(These instructions apply to udisks v1 – if using udisks v2, adjust the commands accordingly – see udisksctl --help)

To test that udisks is working properly on your system (udisks requires dbus):

udisks --show-info /dev/sda   # this triggers udisks daemon start
udisks --monitor

The monitor should report when devices are added or removed.

Make sure you can mount and unmount drives as a normal user. For example, place a data CD or DVD in your drive and:

udisks --mount /dev/sr0
Mounted /org/freedesktop/UDisks/devices/sr0 at /media/cd
ls /media/cd
udisks --unmount /dev/sr0

 

Troubleshooting UDisks

(These instructions are somewhat dated and apply to udisks v1 – if using udisks v2, also lookup ‘Not Authorized’ errors on your distro’s forum for help.)

If udisks reports ‘Not Authorized’ on mount attempts, then the ConsoleKit session is not working properly. There are several active bug reports on this problem, so check your distribution’s bug reports.

You can check if your ConsoleKit session is ‘active’ and ‘local’:

ck-list-sessions

Session15:
  unix-user = '1000'
  realname = '(null)'
  seat = 'Seat1'
  session-type = ''
  active = TRUE
  x11-display = ':0'
  x11-display-device = '/dev/tty8'
  display-device = '/dev/tty1'
  remote-host-name = ''
  is-local = TRUE
  on-since = '2011-02-13T13:31:56.453181Z'
  login-session-id = '11'

However, in some cases ConsoleKit may authorize even when ‘active’ and ‘is-local’ are FALSE (its behavior is unreliable).

On Arch Linux (and possibly other distributions), you may need to add these lines to the file /etc/pam.d/login:

session optional pam_loginuid.so
session optional pam_ck_connector.so

You may need to reboot for this change to take effect.

 
In unusual cases, you may need to explicitly setup PolicyKit to allow members of the storage group to mount and unmount with udisks (usually this is already the case). To do so, create a text file named /etc/polkit-1/localauthority/50-local.d/10-udisks.pkla with this content:

[udisks]
Identity=unix-group:storage
Action=org.freedesktop.udisks.drive-eject;org.freedesktop.udisks.filesystem-mount
ResultAny=yes

Then add your user to the storage group if necessary (replace “myusername” with yours):

sudo usermod -aG storage myusername

Alternatively, you can just give your user permission rather than the whole storage group. In 10-udisks.pkla above change:

Identity=unix-user:myusername

You may need to reboot for this change to take effect.

 
For more information on ConsoleKit issues, see comments on the new instructions, forum discussion, mailing list discussion, ConsoleKit Documentation, and man pklocalauthority.

Also check these bug reports for helpful information:
Arch Bug: consolekit should enable pam_ck_connector.so
Arch Bug: consolekit 0.4.2 “active” and “is-local” always set to FALSE
Gentoo Bug: consolekit-0.4.2: session always ends up as “active” and “is-local” set FALSE

 

Known Issues

esata external drives look like internal drives to devmon and udisks, so devmon won’t normally mount them when they are connected. To work around this issue the ––internal option is provided, which will cause devmon to treat ALL drives as external. In daemon automounting mode, this will cause it to mount any unmounted drives. When used with ––unmount-removable, this will cause it to attempt to unmount every drive on your system. In general it shouldn’t be able to unmount the real internal drives because udisks reports ‘only root can unmount …’. So you can probably just ignore the errors, unless you have drives in fstab with a “user” option. You can also combine the ––internal switch with several ––ignore-device options to ignore your real internal drives. So between the two this should allow for automounting and unmounting of esata drives. For example:

devmon --internal --ignore-device /dev/sda1 --ignore-device /dev/sda2

78 Comments

  1. it did work. but when i eject a dvdrom by pressing the button on the drive, the mountpoint wasn’t automatically removed. in case of usb sticks, everything goes fine. what happened to cdrom?

    Comment by XeCycle | March 14, 2011

    • This is handled by udisks and depends on fstab. If you have a mount point for the optical drive defined in fstab, the mount point is considered permanent and won’t be removed by udisks. If you remove that reference from fstab and delete the mount point for the drive (usually /media/cd or /media/dvd), then udisks should handle optical discs like usb sticks – it will create a folder in media with the name derived from the disc’s volume label, and remove it when you remove the disc.

      But, if you want the mount point for the optical drive to always be the same (eg /media/dvd), then you need the fstab entry, and you need to make sure that mount point exists, and udisks won’t remove it when the disc is removed.

      It doesn’t appear you can have it both ways – either the mount point changes name and is removed, or the mount point is constant and is not removed.

      Comment by igurublog | March 14, 2011

      • well, entries for cd&dvd in my fstab is commented; do i need to remove these COMMENTED lines?

        Comment by XeCycle | March 15, 2011

        • No, commented lines are ignored. Did you also delete the mount point manually? In that case, you might try unmounting the drive before pressing eject. You can assign a keyboard shortcut to both unmount and eject with:

              devmon --eject /dev/sr0

          If that’s still leaving a mount point, you should probably file a bug against udisks. (Use the udisks ––mount and ––unmount commands directly in terms of the bug report.)

          FYI there is no way (that I’m aware of) for a user (or devmon) to control udisks behavior with mount points, except by changing fstab as I described.

          Comment by igurublog | March 15, 2011

  2. Same problem here. No fstab permanent entry, but on eject devmon fails to umount the mounted dvd/cd

    Comment by Anonymous | April 20, 2011

  3. I’m the anonymous of the previous comment.
    The problem is that udisks seems to don’t provide any event on the eject button press, at least this is what I can understand leaving devmon running without &. After the mount the latest printout is:

    Monitoring activity from the disks daemon. Press Ctrl+C to cancel.

    Then nothing, both on eject and inserting again a cd/dvd

    Comment by Menion | April 20, 2011

    • If I understand you correctly, you are inserting a cd and devmon mounts it, then you are ejecting the disc by pressing the eject button on the drive. The disc ejects but the mount point remains. When you then insert a cd again, it is not automounted.

      If you could drop me an email with the output of devmon during the above steps that may be helpful – thanks.

      Also note that you can use the udisks monitor directly with “udisks ––monitor”. If udisks is not generating events when ejecting and inserting a disc, then devmon won’t work. You may need to file a bug report against udisks in that case.

      You can also try “devmon ––eject /dev/sr0” instead of pressing the eject button (associate it with a keyboard shortcut if you like). That will first unmount then eject, which may help.

      Comment by IgnorantGuru | April 20, 2011

  4. Hi
    Yes you have understood perfectly. I’ll provide all The informations, just give me one more day to reconnect the DVD reader.
    But, I can mention that the latest output I read, after having succesfully mounted The DVD, is:

    Monitoring activity from the disks daemon. Press Ctrl C to cancel.

    So I guess it is a udisks issue. The biggest problem is that I’m running averything on a Kurobox, a NAS running Debian squeeze aiming to be a DLNA server, so your suggestion to use the –eject options with a keyboard shortcat is not an option for me since I don’t have any keyboard connected ;)
    I’ve also noticed that Squeeze have udisks version 1.01 (git 2010 version). Unfortunately I can’t build The latest 1.02, because it depends on later GLib and you know that upgrading GLib on a Linux distribution is not safe.
    BTW, what udisks version do you use?

    Comment by Menion | April 21, 2011

    • FYI, devmon does not do automatic unmounting of optical drives [in newer versions since this was written, it does – some of the info here is outdated]. So devmon does not handle what happens when you press eject. This is probably handled by udev in combination with udisks. On my system it generally ejects and unmounts when I press eject. However if vlc has accessed the drive, then I usually need to unmount before the disc will eject (I use “devmon ––eject which does both the unmount and ejection).

      The only thing devmon does is note that an eject has occurred, so when it next sees media in that device it knows to mount it. (Otherwise it would instantly re-mount anything you manually unmount, which is undesirable.)

      So I doubt there is anything in devmon that can be changed to correct your problem. If udisks isn’t providing notification of the ejection, or the subsequent insertion, then devmon can’t do anything about that. But I would be interested to know what is causing the problem.

      In aptosid I currently have udisks version 1.0.2-4. I doubt the version or distro is that critical because otherwise I likely would have heard other bug reports like yours – to date yours is the first report of such a problem.

      Comment by IgnorantGuru | April 21, 2011

      • Also, you might try the following steps with devmon NOT running:

            killall devmon
            udisks --monitor
            # leave the monitor running and in another terminal:
            # insert a cd, and then:
            udisks --mount /dev/sr0
            # check for mount
            mount | grep sr0
            # now press eject and then check for mount:
            mount | grep sr0
            ls -la /media

        You could also test what happens when you unmount before ejecting:

            # insert cd
            udisks --mount /dev/sr0
            mount | grep sr0
            udisks --unmount /dev/sr0
            # now press eject
            mount | grep sr0
        

        Check in the monitor window how those events are reported and you might find a clue.

        Comment by IgnorantGuru | April 21, 2011

        • Hi
          I had to manually set udev rules to automount USB dongle. But, as you know, all this kind of rules, watch for new creation of sdxx devices under /dev, while the dvd/cd block device, in my case sr0 is always present, so udev will not do anything. Do you know which kind of udev rule I could set in order to umount a cd/dvd when pressing eject button?

          Comment by Menion | April 21, 2011

          • I don’t know off-hand how that is handled with udev when eject is pressed. As for automounting, normally no udev rules should be required with udisks & devmon, and might interfere with them. If you’re not able to find another solution, I do suggest you submit a bug report with udisks or at least speak to them about the behavior you’re getting. udisks has proved very reliable in general, but it’s still a young project.

            Comment by IgnorantGuru | April 22, 2011

  5. I am using Ubuntu 10.10. I have an application which I want to run after USB is connected . I have udisks in my system and even if devmon is not there , the cd/usb gets mounted when inserted. Things work find with Udisk, I am looking for a way to run a wvdial application after some 10seconds of delay after inserting the USB. Please suggest a way!!

    Comment by pdas | May 11, 2011

    • If you already have another automounting solution working, you can start devmon with the ––no-mount option so it won’t try to automount anything. Then you can run your program with a 10 second delay something like this:

          devmon --no-mount --exec-on-drive "sleep 10; wvdial" --exec-on-disc "sleep 10; wvdial"

      That will run wvdial when a CD or USB stick is inserted.

      Comment by IgnorantGuru | May 11, 2011

  6. yes, But i am not confident how to use and when to run the devmon. Whether I need to have OpenBox and then I need to edit the autostart.sh or I will use the method of .xinitrc file. Please suggest a better method to do this. Whether the devmon keeps running and when the usb is inserted it will run the wvdial??..or when USb is inserted at that time the devmon starts running?I am a beginner in Linux, please help!

    Comment by pdas | May 12, 2011

    • First I would open a terminal to run devmon as described in the instructions on this page. Test it out while you can see the output and make adjustments to get it the way you want. Open a terminal and run:

          devmon --no-mount --exec-on-drive "sleep 10; wvdial" --exec-on-disc "sleep 10; wvdial"

      Then insert a device. As for autostarting devmon after login, that depends on your window manager. Openbox is not required. I’m not very familiar with Gnome, but this page has a method for autostarting apps in Gnome. In that method, you would enter as the ‘command’:

          devmon --no-mount --exec-on-drive "sleep 10; wvdial" --exec-on-disc "sleep 10; wvdial"

      After login, you can check if devmon is running with:

          ps -fC devmon

      Also, don’t miss the comment at the end of that article:

      Another way to do this is to put a shortcut (filename.desktop) into the folder ~/.config/autostart. If this folder doesn’t exist, simply create it. BTW, in Ubuntu the path to the aforementioned program is System -> Preferences -> Startup Applications.

      It sounds like you could also create a new text file named “~/.config/autostart/devmon-start” with these contents:

          #!/bin/bash
          devmon --no-mount --exec-on-drive "sleep 10; wvdial" --exec-on-disc "sleep 10; wvdial" &

      Save it and make it executable:

          chmod +x ~/.config/autostart/devmon-start

      Comment by IgnorantGuru | May 12, 2011

    • Also see this post on Ubuntu Forums.

      Comment by IgnorantGuru | May 21, 2011

  7. thanks for the great scripts! it works very well.

    i used it on Ubuntu. is it possible for the scripts:

    1. let me choose specific mount option based on filesystem

    e.g. flush for vfat, sync for ntfs/ext2/ext3/ext4

    2. respect the UDISKS_PRESENTATION_NOPOLICY of udisks

    for the man page of udisks

    UDISKS_PRESENTATION_NOPOLICY
    If set to 1 this is a hint to presentation level software that the
    device should not be automounted or autoassembled (for e.g.
    components of a multi-disk device).

    Anyways, thank for the great script again

    Comment by c | May 19, 2011

    • On 1, for that level of control I would suggest either modifying the devmon script, or use the ––no-mount option to disable automounting, then use ––exec-on-… options to call a custom script which conditionally mounts based on fs type (which you can get from `udisks ––show-info DEVICE`). You could also leave automounting enabled and use a script to conditionally remount. I have noted the issue and will look over the feasibility of adding something to devmon to make this easier, but its unlikely due to the usage complexity it would introduce.

      On 2, I should be able to include that in the next update.

      Thanks for your feedback.

      Comment by IgnorantGuru | May 20, 2011

      • thank you very much

        For 1, i do agree that allowing mount option for different kind of filesystem will make the script too complicated to use

        but sync/flush mount option are quite common for removable device to prevent data loss

        how about a new parameter?

        –mount_with_sync

        add mount option “sync” when mounting removable storage (exception for vfat, “flush” will be added, “sync” is too slow for use)

        this parameter should not be difficult

        Comment by c | May 20, 2011

        • Excellent idea – thanks. In fact I’ll consider making sync mount the default, although for whatever reason udisks does not.

          UPDATE: devmon 1.0.1 includes a ––sync option, and should also obey UDISKS_PRESENTATION_NOPOLICY. Due to flush only being supported by kernels 2.6.19 and later, some problems reported with flush on some kernels, and sync causing slow writing, I didn’t make sync the default.

          Comment by IgnorantGuru | May 20, 2011

          • thank you very much. this is really quick

            Comment by c | May 21, 2011

          • there is no “sync” option when mounting filesystem ntfs

            is it possible to include this too?

            Comment by c | May 21, 2011

            • It’s been awhile since I’ve used ntfs under linux. Isn’t ntfs still read-only, meaning sync would not apply? Or does udisks mount ntfs filesystems with ntfs-3g?

              Also, I see no mention of ntfs in the mount sync docs. Some fstypes don’t support sync and simply ignore the option.

              Comment by IgnorantGuru | May 22, 2011

              • i am using ubuntu

                i tested it, by default, udisks mount with ntfs-3g

                in the release history of ntfs-3g

                http://www.tuxera.com/community/release-history/

                “sync” is implemented in “STABLE Version 2011.1.15 (January 23, 2011)”

                i tested if i mount with “sync” for ntfs partition, the “sync” option is displayed in mtab

                Comment by c | May 22, 2011

                • Sounds reasonable – thanks for looking into it.

                  Comment by IgnorantGuru | May 22, 2011

  8. I installed devmon 1.0.1 but it doesn’t recognize ––sync or -s as a valid option. Yet running devmon ––help does show those two options available.

    Comment by Kevin | May 22, 2011

    • Maybe you have two copies of devmon in your path, one being a previous version? Try

          which -a devmon

      Which should list just one location. Otherwise please let me know the full command line you’re using and what message you’re receiving so I can try to duplicate the problem – I can’t see how ––sync wouldn’t be recognized if you’re running 1.0.1.

      Comment by IgnorantGuru | May 22, 2011

      • I uninstalled and reinstalled and it seems to be working fine now. Thanks.

        Comment by Kevin | May 22, 2011

  9. Hello,

    Debian Squeeze here.
    I use devmon with Rox-filer and I can’t unmount devices within Rox-filer when there are spaces within the volume label. It seems not to be a fault of devmon, since it uses udisks/consolekit.
    I “solved” with a workaround.
    Click on the mount point (SANDISK in the screenshot here) and choose “Customize Menu”. A Window will open. Create a script file named “unmount.sh” inside the folder ~/.config/rox.sourceforge.net/SendTo/.inode_mount-point

    unmount.sh should contain the following:

        #!/bin/bash
        sync
        devmon --unmount "$1"

    And make the file executable. Now you can use this instead of the rox built-in unmount command.

    Hope this helps someone.

    Comment by Davide R | July 3, 2011

  10. Packaged on frugalware linux :)

    http://frugalware.org/packages/119874

    Comment by Daniel (@devil505) | August 21, 2011

    • Thanks for letting me know – I’ve added it to the download links above. Frugalware looks interesting – I need to check that out.

      Comment by IgnorantGuru | August 22, 2011

  11. Hey, thanks for your great work! Just a small problem, I seem to miss somthing: Any –exec-on options won’t work here. Same with –info-on-mount. Automounting works perfectly! I’m trying the following:

    devmon –exec-on-drive “touch /home/max/TEST” –exec-on-disc “touch /home/max/TEST”

    Also tried as root, with “mplayer xx.ogg” […]. The output of devmon running in console doesn’t give any notices concerning the –exec commands. Should it do so? What do I miss?

    Comment by Max | August 27, 2011

    • Sorry, have to retract my last post. –exec and –info-on-mount is working fine when devmon ist started *before* the drive is plugged in. I left it plugged in and started devmon afterwords, executing commands did not work then. Maybe a bug? By the way, –exec-on-video *did* work even in this case! Anyway, working great now, big thanks!

      Comment by Max | August 27, 2011

      • Thanks for your feedback. As you found, on initial startup devmon will mount optical discs and removable drives if present and unmounted, but will not execute commands (by design).

        Comment by IgnorantGuru | August 27, 2011

  12. Devmon doesnt exec script on label. It works some time ago, but stopped after some update. I use Arch and XFCE and try to ue devmon for backup my flash drive on mount. So /dev/sdc1 has label SYSRESC and i run
    /usr/bin/devmon –exec-on-label SYSRESC /usr/local/bin/backup.sh
    It mounts drive on insert but doesnt execute proper script. My skills in shell scripting are not enough to know devmon internal logic. Output from devmon runned in terminal:

    Monitoring activity from the disks daemon. Press Ctrl+C to cancel.
    ===========================================
    added: /org/freedesktop/UDisks/devices/sdc
    ===========================================
    added: /org/freedesktop/UDisks/devices/sdc1
    device: [/dev/sdc1]
    systeminternal: [0]
    usage: [filesystem]
    type: [vfat]
    label: [SYSRESC]
    ismounted: [1]
    nopolicy: [0]
    hasmedia: [1]
    opticaldisc: []
    numaudiotracks: []
    blank: []
    media: []
    partition: [1]
    ===========================================
    job-changed: /org/freedesktop/UDisks/devices/sdc1
    ===========================================
    job-changed: /org/freedesktop/UDisks/devices/sdc
    ===========================================
    changed: /org/freedesktop/UDisks/devices/sdc1
    device: [/dev/sdc1]
    systeminternal: [0]
    usage: [filesystem]
    type: [vfat]
    label: [SYSRESC]
    ismounted: [1]
    nopolicy: [0]
    hasmedia: [1]
    opticaldisc: []
    numaudiotracks: []
    blank: []
    media: []
    partition: [1]
    ===========================================
    job-changed: /org/freedesktop/UDisks/devices/sdc1
    ===========================================
    job-changed: /org/freedesktop/UDisks/devices/sdc

    This output generated after inser, unmount and drive remove seems correct. Using of –ignore-label doesnt change anything.

    Thanks

    Comment by Vadym Markov | November 16, 2011

    • It appears that something is auto-mounting the drive before devmon, which means devmon doesn’t do the mount, thus exec-on-label doesn’t execute. This could mean you have another instance of devmon running at the same time (without exec-on-lablel), or you have another automounting solution in place.

      This is evident from the first report of “ismounted: [1]”. If no other automounting solution is working, this should report “”ismounted: [0]”, which triggers devmon to mount it and execute commands. Also, devmon is not reporting that it mounted the drive (see example below).

      Here is my test inserting a drive with label ‘SYSRESC’:

      $ devmon --exec-on-label SYSRESC "echo XXXXX"
      
      added:     /org/freedesktop/UDisks/devices/sdd1
      device: [/dev/sdd1]
          systeminternal: [0]
          usage:          [filesystem]
          type:           [vfat]
          label:          [SYSRESC]
          ismounted:      [0]
          nopolicy:       [0]
          hasmedia:       [1]
          opticaldisc:    []
          numaudiotracks: []
          blank:          []
          media:          []
          partition:      [1]
      devmon: mount /dev/sdd1 --mount-options noexec,nosuid,noatime    (SYSRESC)
      Mounted /org/freedesktop/UDisks/devices/sdd1 at /media/SYSRESC
      devmon: [exec on label] eval echo XXXXX
      XXXXX
      [SNIP]
      changed:     /org/freedesktop/UDisks/devices/sdd1
      device: [/dev/sdd1]
          systeminternal: [0]
          usage:          [filesystem]
          type:           [vfat]
          label:          [SYSRESC]
          ismounted:      [1]
          nopolicy:       [0]
          hasmedia:       [1]
          opticaldisc:    []
          numaudiotracks: []
          blank:          []
          media:          []
          partition:      [1]
      [SNIP]
      

      Comment by IgnorantGuru | November 17, 2011

  13. Yes, it seems to conflict with XFCE automounter. But i removed volume manager package. Without running X session devmon works flawlessly. Is it some way to check which program intercept USB stick inserting and mount it before devmon?

    Comment by Vadym Markov | November 17, 2011

  14. It was gvfs. It needed by some not-so-useful-for-me packages, so i remove it. Maybe you should do some comment in Installation about it if it will be confirmed

    Comment by Vadym Markov | November 17, 2011

    • I don’t believe just having gvfs installed will be a problem, but if a client such as Thunar has been configured to automount via gvfs, then it may preempt devmon, as it did in your case. I have added a note to the install instructions – thanks for your feedback.

      Comment by IgnorantGuru | November 18, 2011

  15. First, thank you for this script: I like to have a user friendly interface while avoiding all the dependencies involved with the latest incarnations of Gnome or KDE. Your script helped a good deal in this regard.

    User friendliness is important to me because my computer (running arch linux) is used by several people (’cause it’s connected to a big stereo in my living room) who know only Windows. Often these people bring USB drives or CD/DVDs with music on it. I worked to have a little tray icon allowing these windozed people to umount their USB drive or eject their CD/DVD. I had to hack your script to be able to let people choose what they want to eject or umount.

    All this long story, to tell you that it would be nice to have options to list removable disks and ejectable CDs in order to call back your script to perform the choosen action.

    Thanks again,

    Xavier

    Comment by Xavier | December 18, 2011

    • So you’re thinking a space-separated list: /dev/sr0 /dev/sdd1 … ?

      Thanks – I’ve made a note for that and will look it over.

      Comment by IgnorantGuru | December 20, 2011

  16. –exec-on-remove and -on-unmount with %d does not work for me. If I remove flashdisk I can see “devmon: [exec on remove] eval echo ” &
    the command was –exec-on-remove “echo %d”
    Devmon keeps the directory in /media/someflashdrive when I remove the drive so I want to remove it with –exec-on-remove “rmdir %d”

    thank you for help

    Comment by Honza | December 20, 2011

    • Currently, devmon clears the mount point variable and label when the device is removed, as they are no longer valid, so %d and %l won’t work. I’ll look that behavior over the next time I work on it. I can probably leave them intact.

      FYI, udisks will generally remove the /media/… directory providing that it isn’t hard-coded in fstab for that device (eg /media/dvd). That’s why %d is unlikely to be useful – the mount point should be gone. The only time it doesn’t remove them for me is if I shutdown without first explicitly unmounting the device. That is why devmon unmounts all devices on exit by default.

      If you want to hack it, open the script in your editor, find this section at the end and remove the unset line:

      if (( execorx != 0 )); then
          if ( ! ignoredevice "$devpath" ); then
              unset lb point
              dv="$devpath"
              execcommands "exec on remove" "${execor[@]}"
          fi
      fi
      

      Comment by IgnorantGuru | December 20, 2011

      • Thank you. In my case I always remove the device without unmout. I have LTSP – linux terminal server – with fluxbox and xfreerdp. Thin client boots from the network, starts fluxbox and devmon and then starts xfreerdp to the windows terminal server in fullscreen. Every device in /media/* is accessible in windows term.serv. as shared disk and because of that it is not possible to unmount it from windows. Devmon has –sync parameter which is good for removing device without unmount. And this is the reason why I need to delete the directories in /media after “unsafe” device remove. I will try your advice asap.

        Comment by Honza | December 20, 2011

        • I think under those circumstances (entire device removed) udisks should be removing the directory, so you might file a bug on that. I could also have devmon attempt to remove it, but I’ll have to see what the implications are. At the very least, it can probably leave %d’s value intact.

          Comment by IgnorantGuru | December 20, 2011

          • Hello. Today I tried remove the unset line but it does not help, directory is still present. Thank you for advice.

            Comment by Honza | January 2, 2012

            • Maybe now I can see the problem. After removing the device, this device is still in mount list of devices.

              Comment by Honza | January 2, 2012

              • Removing the unset line won’t affect the directory, but it should mean that when devmon executes your ––exec-on-remove command, the value of %v (eg /dev/sdd1) is passed to your command. The unset line clears that value before running your command.

                As for udisks behavior, it thinks the device is still mounted, so it doesn’t remove the directory. I think this is a udisks bug – if the device is removed it should unmount it and remove the directory automatically.

                Comment by IgnorantGuru | January 2, 2012

                • Hello. Now I have the unset line removed and in exec I call umount %d and rmdir %d and that is exactly what I need, it works perfectly :-)
                  Thank you

                  Comment by Honza | January 4, 2012

  17. Good day

    I’ve used your script to help others by providing an automatic sort for USB drives on unmount with feedback. My code contribution really is not that huge: a startup wrapper and a script which does the actual fatsort call with a progress dialog. The project can be found here:
    http://code.google.com/p/autofatsort/
    I give credit to you for devmon (though I can’t by real name as I don’t know it) and there’s a version of the devmon script hosted there for the sake of convenience (or for the unhappy event that this blog goes missing ): ). If you’re unhappy about a copy being hosted there, please msg me and I’ll remove it. I understand the GPL license should allow me to do so, but IANAL (:

    Thanks again.

    Comment by Davyd McColl | February 26, 2012

    • Thanks – interesting approach. If you ever try spacefm, it includes most of the functionality of devmon too, so this could be a done as a spacefm plugin too. Or spacefm users can simply run your script from a custom command. I may put a link at the top here shortly.

      Comment by IgnorantGuru | February 28, 2012

  18. I just wanna say thanks a zillion for the script. It works really great!

    Comment by Os | April 20, 2012

  19. I wrote a blog post on devmon last year, and first I’d like to say thanks (again!) for writing this script – it’s working wonderfully on my Eee 701, and I’m about to try it on my new Raspberry Pi (running Arch Linux ARM). Great work :-)

    Quick question: if I start devmon automatically from ~/.xinitrc, does that mean it won’t be running if I am not in an X session? I’d quite like to have automounting drives at the console too – is there any reason why devmon can’t be run from ~/.bashrc or ~/.bash_profile, for instance?

    Much appreciated!

    Comment by Tim | May 25, 2012

    • Glad to hear devmon is working well for you – the Pi experiment will be interesting. If started from xinitrc, it does mean devmon won’t be running unless you’re logged into an X session. You can certainly run devmon outside of X, just insure there is only one devmon running or it can get confusing. The main question in this case is what will udisks allow you to do in terms of mounting, as udisks authorizes users through policykit and consolekit. Ideally it should work, but these kits and udisks have near random behavior at times.

      There are also some changes coming to devmon shortly. With versions after 1.0.5, support will be added for the new udevil. Depending on how this update goes, udevil may be required by devmon due to some of the less-than-functional changes introduced in udisks2. So please keep an eye on the blog for notices on the upcoming changes.

      Comment by IgnorantGuru | May 25, 2012

      • Thanks for your quick reply – I don’t think the RasPi will present problems for devmon, as Arch Linux ARM is surprisingly similar to its x86 counterpart, and so far I’ve been able to set things up similarly. (I use Fluxbox as the X window manager on both machines, hence my running devmon to help with removable drives.)

        I’ll keep an eye out for the changes you mentioned; in the meantime, I should also pass on a tip for Arch Linux. I think there must have been a recent change to consolekit, udisks or one of these subsystems, as devmon would return the “not authorised by consolekit” dialogue box on every X login (instead of every now and then). Usually, running devmon again would get it working, but I was a bit puzzled by why this suddenly started happening.

        I think it was in an Arch forum post, that someone suggested changing this line in ~/.xinitrc:

        exec ck-launch-session bash -c “devmon [OPTIONS] & startfluxbox”

        to:

        exec startfluxbox

        Since doing this, devmon not only no longer pops up the dialogue box, but it appears to work with no problems again – maybe this will help someone?

        Comment by Tim | May 25, 2012

        • Thanks for the fluxbox info. The details on devmon 1.1.0 are here.

          Comment by IgnorantGuru | May 25, 2012

    • Hi, I just recently got my RaspberryPI. I can confirm that devmon works well on it for automount my external CD/DVD drive. LXDE does automount CD/DVD’s when running, but I wanted automount from the console as I don’t often run LXDE. I placed a line to auto-start devmon in the /etc/rc.local file. You need to sudo -u pi if you want devmon to mount cd/dvd’s that can be accessed by user PI as far as I know, otherwise it mounts them so only root can access it.

      The command I use is sudo -u pi sh -c “/usr/local/bin/devmon –exec-on-drive ‘myscript.sh’ 2>&1 > /var/log/devmon.log”

      This does mean however that my script will execute even if no-one has logged in yet, so if you’re security concious, this might not be the best approach

      The only minor issue I have found is that if I put an old/badly burnt DVD in the drive and the drive cannot read it, devmon spits out a “disc ejected” message even though the disk doesn’t actually eject. This then causes other events not to register (i.e. physically ejecting the disc and putting a new one in) unless i actually issue the eject /dev/sr0 or devmon –eject /dev/sr0 command.

      Does anyone know if there is a way for devmon to catch “unreadable disc” state or using udev/udisks. Udisks seems to report no media after the drive clicks and whirs for a couple of minutes in an attempt to read the disc

      Comment by Wassy | August 8, 2012

  20. I have installed devmon on my wife’s Arch box so that she can seamlessly mount her Sony MP3 player and then run the “JSymphonic” app for that player. However, “devmon” mounts to different mountpoints and the player app needs a consistent name. How can I force devmon to use the same mountpoint each time the MP3 player gets mounted?

    Comment by lggagnon | July 11, 2012

    • Several ways to do this…

      1) You can add the device to fstab with a specific mount point, and create that mount point as root.

      2) You can set a volume label for the filesystem – most mount solutions will use the label as the mount point. Not sure how consistent udisks is with this, but if you use devmon with udevil installed, udevil will mount to /media/LABEL. udevil is also more consistent than udisks if the device doesn’t have a label.

      3) You can use devmon’s exec-on-drive to pass the mount point to a script or app (%d). If the app can’t take a mount point spec, you could have a script dynamically create a link to the mount point using a consistent name for the link.

      Comment by IgnorantGuru | July 12, 2012

  21. Thank you for your useful script.

    I have used it to make a device that copies a directory from disk to every usb memory that is inserted http://www.medialab.ufg.br/site/#res6-programa-de-residencia-artistica-e-cientifica . I have successfully done it via root with the following command:
    devmon –exec-on-drive “cp -r ./media_files %d ; umount %d”
    Nevertheless, it will not do the unmounting if run as regular user.

    The device’s final objective are to detect insertion of a usb memory on a specific usb port, mount it, copy the contents of the media_files directory on the hard disk to the usb memory and then unmount it. On the other hand, the device should detect insertion of a usb memory on another specific usb port, mount it, copy the contents of the media_files directory on the usb memory to the hard disk and then unmount it.

    Do you have any suggestions of the commands to use or modifications to make to your script? Thank you very much for your pointers.

    Comment by Quiliro | October 14, 2012

    • Hi, Regarding:

          devmon --exec-on-drive "cp -r ./media_files %d ; umount %d"

      Because you’re asking devmon to run umount directly, the usual permissions for umount will apply – a normal user won’t be authorized. Instead, have devmon (the daemon) run devmon (the client) to do the unmount:

          devmon --exec-on-drive "cp -r ./media_files %d ; devmon --unmount %d"

      This way you won’t need to run it as root. devmon the client will use whatever mount solution you have installed to unmount as a normal user (udevil, udisks2, udisks1, or pmount).

      Comment by IgnorantGuru | October 17, 2012

  22. Thank you for your great script.

    I am using devmon in the making of an appliance that is intended for sharing files. It will have no interface except for two USB ports. One is for downloading a folder with some files FROM the device and the other for uploading a folder with files TO the device.

    In this quest, it is necesary that one USB port (regardless which USB memory is plugged into it) executes one action on detection of a USB memory (copy a folder FROM the device TO the USB memory) and the other USB port (regardless which USB memory is plugged into it) executes another action on detection of a USB memory (copy a folder TO the device FROM the USB memory).

    I have tested devmon with the following parameters:
    devmon –exec-on-drive “cp -r /home/quiliro/media %d ; umount %d” # successful as root
    devmon -s –exec-on-drive “cp -r /home/quiliro/media %d” # successful as user

    While these commands do a good job, they will not distinguish which port they are plugged into. So to identify the ports, I have created a udev rule file (/etc/udev/rules.d/65-usb_derecho.rules):

    ACTION==”add”, ENV{ID_PATH}==”pci-0000:00:12.2-usb-0:2:1.0-scsi-0:0:0:0″, SUBSYSTEMS==”usb”, SYMLINK+=”usb_izquierdo”

    I made this rule based on the following:

    udevadm info –query=all –name=/dev/disk/by-path/pci-0000\:00\:12.2-usb-0\:2\:1.0-scsi-0\:0\:0\:0-part1 | head -n1
    P: /devices/pci0000:00/0000:00:12.2/usb1/1-2/1-2:1.0/host46/target46:0:0/46:0:0:0/block/sdb/sdb1

    udevadm test /devices/pci0000:00/0000:00:12.2/usb1/1-2/1-2:1.0/host46/target46:0:0/46:0:0:0/block/sdb/sdb1 |grep usb_
    […]
    creating link ‘/dev/usb_izquierdo’ to ‘/dev/sdb1’
    preserve already existing symlink ‘/dev/usb_izquierdo’ to ‘sdb1’
    unload module index
    DEVLINKS=/dev/disk/by-id/usb-Kingston_DT_101_G2_001372971AEABA60561308CF-0:0-part1 /dev/disk/by-path/pci-0000:00:12.2-usb-0:2:1.0-scsi-0:0:0:0-part1 /dev/disk/by-uuid/B1AD-E70B /dev/usb_izquierdo

    So, once the rule is set up, i have tryed the following commands:

    devmon –exec-on-device /dev/usb_izquierdo “cp -r /home/quiliro/media %d ; umount %d” # unsuccessful

    devmon –exec-on-device /dev/sdb1 “cp -r /home/quiliro/media %d ; umount %d” # successful

    Nevertheless, sdb1 could change. How can I use the symlink (or any other) method to execute the command on any USB memory pluged into a specific USB port?

    Please provide information on how to contribute (don’t have money) to any task you need help in. I feel the need to contribute back regardless of the help I get about this post.

    Comment by Quiliro | October 16, 2012

    • To do this, I would have devmon run a custom script when a drive is mounted:

          devmon --exec-on-drive "custom-script.sh %f %d"

      In the custom-script, run udevil or udisks to get info on $1 (eg %f == /dev/sdb1) ($2 will be the mount point to copy files to/from in the script). When you run udevil info $1 from custom-script, one of the output lines will show the native-path. You can then parse this to determine the usb port in use. Once it knows this, your script can then take the desired action, such as copying files to/from the device and then unmounting it (run devmon --unmount $1).

      An example custom-script.sh using udevil for the info:

      #!/bin/bash
      
      native_path=`udevil --show-info $1 | grep "^  native-path:" | \
                              sed 's/^  native-path: *\(.*\) */\1/'`
      usb_port="${native_path##*/usb[[:digit:]]/}"
      usb_port="${usb_port%%/*}"
      
      case "$usb_port" in
          "1-1" )
              echo "do copy TO device $1 on port $usb_port"
              # put some code here
              ;;
          "1-2" )
              echo "do copy FROM device $1 on port $usb_port"
              # put some code here
              ;;
          "" )
              echo "usb port for device \"$1\" could not be determined"
              exit 1
              ;;
          * )
              echo "usb port $usb_port for device $1 ignored"
      esac
      
      sync
      devmon --unmount $1
      

      Or if not using udevil, udisks v1 has the same usage for info, so just change “udevil” to “udisks” in the above script. udisks2 uses udisksctl for info and has a different usage and output format.

      Thanks for the help offer but not much is pending for devmon – I just need to add support for SpaceFM Dialog so it will use that in place of zenity. This should be in the next release.

      Comment by IgnorantGuru | October 17, 2012

      • Thank you very much .

        The only problem I have is with %d when the volume’s label contains a name with spaces. It will rsync with only the part of the name before the space. So it will not find the mount directory.

        This is my final version. Please tell me if you are OK with the license.

        #!/bin/bash
        
        # Copyright (C) 2012 Quiliro Ordóñez and IgnorantGuru
        #
        # This program is free software: you can redistribute it and/or modify
        # it under the terms of the GNU Affero General Public License as
        # published by the Free Software Foundation, either version 3 of the
        # License, or (at your option) any later version.
        #
        # This program is distributed in the hope that it will be useful,
        # but WITHOUT ANY WARRANTY; without even the implied warranty of
        # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
        # GNU Affero General Public License for more details.
        #
        # You should have received a copy of the GNU Affero General Public
        # License along with this program.If not, see
        # .
        #
        # https://igurublog.wordpress.com
        # quiliro [at] fsfla [dot] org
        #
        
        native_path=`udevil --show-info $1 | grep "^  native-path:" | \
                                sed 's/^  native-path: *\(.*\) */\1/'`
        usb_port="${native_path##*/usb[[:digit:]]/}"
        usb_port="${usb_port%%/*}"
        
        sleep 1
        case "$usb_port" in
            "1-1" )
                echo "copy TO device $1 on port $usb_port"
                rsync -a /home/bom/bom_compartilhar $2/
                ;;
            "1-2" )
                echo "copy FROM device $1 on port $usb_port"
                rsync -a $2/bom_compartilhar /home/bom/
                ;;
            "" )
                echo "usb port for device \"$1\" could not be determined"
                exit 1
                ;;
            * )
                echo "usb port $usb_port for device $1 ignored"
        esac
        
        devmon --unmount $1
        

        Comment by Quiliro | October 17, 2012

        • If you double quote the “$2” for rsync that should handle spaces:

              rsync -a /home/bom/bom_compartilhar "$2/"
              rsync -a "$2/bom_compartilhar" /home/bom/

          License is fine – you can use that example script however you like. You might want to note at the top of your comments that the script requires udevil. Or if publishing, you might want to have the script discover udevil or udisks (v1) and use whatever is installed (see the devmon script for how this can be done with ‘which’).

          Comment by IgnorantGuru | October 17, 2012

          • Thank you for your sggestions. They helped me finish the project. This is my final version of the script instructing the user to install udevil and other packages as specified in http://pastebin.com/HsJZZqWM :

            #!/bin/bash

            # Copyright (C) 2012 Quiliro Ordóñez and IgnorantGuru
            #
            # This program is free software: you can redistribute it and/or modify
            # it under the terms of the GNU Affero General Public License as
            # published by the Free Software Foundation, either version 3 of the
            # License, or (at your option) any later version.
            #
            # This program is distributed in the hope that it will be useful,
            # but WITHOUT ANY WARRANTY; without even the implied warranty of
            # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
            # GNU Affero General Public License for more details.
            #
            # You should have received a copy of the GNU Affero General Public
            # License along with this program.If not, see
            # .
            #
            # https://igurublog.wordpress.com
            # quiliro [at] fsfla [dot] org
            #
            #
            # Instructions to replicate:
            #
            # Copy the operating system to another USB memory by changing to the
            # directory where the image is and executing this command:
            # dd if=bom_compartilhar.img of=/dev/sdb
            # where sdb is the device corresponding to the destination USB memory.
            # You should type:
            # mount
            # to discover which devices are currently mounted and deduce which one
            # is you destination USB memory. Then unmount the destination USB
            # memory and proceed to copy the operating system.
            #
            # Configure Num Lock to OFF in BIOS.
            #
            # Note: If you didn’t copy the operating system from my image, you
            # should install the necesary packages. On Parabola GNU, the command
            # is:
            # pacman -S udevil rsync dosfstools sudo
            #
            # In order to start this program on boot, at the end of Parabola’s
            # /etc/rc.local file, add:
            # devmon –exec-on-drive “/home/bom/copiar_usb.bash %f %d” &
            # setleds -num +caps -scroll < /dev/tty1 &
            #
            # Keep hacking this script and let us know your progress!
            #

            keyboard="/dev/tty1"

            echo
            echo "Changing Caps Lock to OFF"
            setleds -caps < $keyboard

            native_path=`udevil –show-info $1 | grep "^ native-path:" | sed 's/^ native-path: *\(.*\) */\1/'`
            usb_port="${native_path##*/usb[[:digit:]]/}"
            echo
            echo "native_path is " $native_path
            echo "usb_port is " $usb_port
            usb_port="${usb_port%%/*}"
            echo "Now usb_port is " $usb_port
            echo

            echo "%f device filesystem – is " $1
            echo "%d mount directory – is " $2
            echo

            case "$usb_port" in

            "1-1" )
            echo
            echo "Changing Num Lock to ON"
            setleds +num < $keyboard

            ## One attempt at erasing the recycle bin:
            # echo "Testing if enough space is left on the device"
            # contents="du -s /home/bom/bom_compartilhar"
            # (( $( read -d '' -ra df < <(LC_ALL=C df -P "$1" ); echo "${df[10]}" ) < contents)) && echo rm -rf "$2"/.Trash*;
            #
            ## Another attempt at erasing the recycle bin:
            # free_space=$(df | grep $1 | awk '{ print '$4'; }')
            # if [ $contents -lt $free_space ]; then
            # echo "Not enough free space on $2. Erasing Trash bin."
            # find $2 -name ".Trash*" -exec rm -rf {} \;
            # fi

            echo
            echo "Downloading to device $1 on port $usb_port mounted on $2"
            echo
            rsync -a /home/bom/bom_compartilhar "$2"/
            ;;

            "2-1" )
            echo
            echo "Changing Scroll Lock to ON"
            setleds +scroll < $keyboard
            echo
            echo "Uploading from device $1 on port $usb_port mounted on $2"
            echo
            rsync -a "$2"/bom_compartilhar /home/bom/
            ;;

            "" )
            echo "usb port for device \"$1\" could not be determined"
            exit 1
            ;;

            * )
            echo "usb port $usb_port for device $1 ignored"

            esac

            devmon –unmount $1
            echo
            echo "Changing Caps Lock to ON and the others to OFF"
            setleds -num +caps -scroll < $keyboard
            ## End of script

            I had two problems:
            – I could not empty the trash bin if the space was not enough ( I commented out those lines in the script)
            – I could not load the command to run the script on boot (on rc.local) as a normal user with:
            sudo -u bom devmon –exec-on-drive "/home/bom/copiar_usb.bash %f %d" &
            I had to do it as root with:
            devmon –exec-on-drive "/home/bom/copiar_usb.bash %f %d" &
            But I don't think these problems are not related to devmon.

            Comment by Quiliro Ordóñez | November 1, 2012

  23. Dear IgnorantGuru:
    I had tried this command:

    devmon --exec-on-drive "rox %d"

    But devmon only mount the usb drive on /media/sdb1, not open this directory with rox.

    How do I deal with this problem? Thanks a lot!

    Best Regards,
    Minhsien

    Comment by Minhsien | February 6, 2013

    • Hi, You can run the devmon command in a terminal and watch the output. It will provide details on what it’s doing – you should see the rox command being issued after the mount command. It’s also possible that some other automount solution (eg spacefm, thunar, etc) is automounting the USB drive before devmon, in which case devmon won’t run anything (the exec-on-drive will only execute if devmon does the mount). Only one automount solution should be used, otherwise it gets confusing.

      Comment by IgnorantGuru | February 6, 2013

  24. Dear IgnorantGuru:

    I post the output in the terminal below, but there is nothing about rox.
    And I checked the mounted devices list, /dev/sdb1 is not mounted yet.
    Should I check any other thing?
    Thanks for your quickly reply.

    Best Regards,
    Minhsien

    ———-
    Poll for media failed: Not Authorized
    ===========================================
    Monitoring activity from the disks daemon. Press Ctrl+C to cancel.
    ===========================================
    added: /org/freedesktop/UDisks/devices/sdb
    ===========================================
    added: /org/freedesktop/UDisks/devices/sdb1
    device: [/dev/sdb1]
    systeminternal: [0]
    usage: [filesystem]
    type: [vfat]
    label: []
    ismounted: [0]
    nopolicy: [0]
    hasmedia: [1]
    opticaldisc: []
    numaudiotracks: []
    blank: []
    media: []
    partition: [1]
    devmon: /usr/bin/pmount /dev/sdb1

    ===========================================
    changed: /org/freedesktop/UDisks/devices/sdb
    ===========================================
    changed: /org/freedesktop/UDisks/devices/sdb1
    device: [/dev/sdb1]
    systeminternal: [0]
    usage: [filesystem]
    type: [vfat]
    label: []
    ismounted: [1]
    nopolicy: [0]
    hasmedia: [1]
    opticaldisc: []
    numaudiotracks: []
    blank: []
    media: []
    partition: [1]
    ——————-

    Comment by Minhsien | February 6, 2013

    • I can confirm that devmon is failing to run exec-on-drive when pmount is used as the mount solution. I have opened an issue on this here (which also shows a temporary workaround). Thanks for the report.

      Comment by IgnorantGuru | February 6, 2013

    • This should now be corrected – you can download the fixed version of devmon. This fix will be included in the udevil 0.3.7 release (devmon is distributed as part of udevil).

      Comment by IgnorantGuru | February 6, 2013

      • Dear IgnorantGuru:
        The new script worked fine now, thank you very much!!!

        Do we have any options to make mondev ignore the ext4 partition?
        This need come from that I have a bootable usb disk with 2 partitions (a Debian system on /dev/sdb1 with ext4 format and a vfat partition on /dev/sdb2). I just want devmon mount the vfat partition automatically, but not the Debian system partition.

        Thanks for your help.

        Best Regards,
        Minhsien

        Comment by Minhsien | February 6, 2013

        • devmon cannot ignore ext4 partitions (unless you edit the script), but you can use ––ignore-device and ––ignore-label to ignore particular partitions by device name or volume label.

          Also, if you install udevil, udevil.conf can be configured to refuse mount permission for ext4 filesystems, so when devmon tells udevil to mount it, it will refuse.

          Comment by IgnorantGuru | February 6, 2013

          • Dear IgnorantGuru:
            Thanks for your advice.
            First I give the partition a label ( tune2fs -L Debian /dev/sdb1 ), and tell devmon not to mount it (
            devmon –ignore-label Debian –exec-on-drive “rox %d” ).
            Now devmon really not auto mount the Debian partition! It works perfectly!!!
            Thank you so much!

            Best Regards,
            Minhsien

            Comment by Minhsien | February 6, 2013

  25. Thank you so much for udevil and devmon! devmon saved me a lot of headache after I upgraded to KDE-4.11, which works with udisks2 and can’t auto-mount optical drives anymore (perhaps a temporary situation though). I searched Internet for hours and couldn’t enable auto-mount until I found udevil.

    Deb package making was very easy by using cdbs. Everything about udevil is so clean, so practical. This project is really promising. Keep up the good work! I hope udevil will come to Debian repositories.

    Comment by Tsu | November 21, 2013

    • Tsu, Thanks for your feedback – that is the kind of problem udevil was created to solve. I haven’t tested it, but the packages for udevil in Mateusz Łukasik’s Ubuntu PPA may work for debian, as udevil is quite simple to install. Mateusz is Debian’s SpaceFM packager, and he has been working on getting udevil in Debian too. I see here that udevil is in Debian’s new queue since June.

      Comment by IgnorantGuru | November 21, 2013