Ubuntu – How to temporarily suspend Nautilus filesystem automounting, without making permanent changes to the system and user configuration

nautilusudevudisksusb-driveusb-storage

I have written a tool which automatically formats and copies files to USB flash drives when they are inserted. It needs the drive to be unmounted to format it.

Normally Nautilus will automatically mount the drive when inserted, so I have to wait for this to happen and then unmount the drive before formatting it. The only problem is that if the user has disabled automounting then my program will wait forever.

I could change the dconf auto-mount setting when my program starts, and then change it back when it exits, but this is not a good solution because the setting wil not be restored if my program crashes.

How can I temporarily prevent Nautilus from automounting USB drives only during the time when my program is running?

Best Answer

You may use PROGRAM to check if your program is running to activate that UDEV rule, otherwise it is disabled because pgrep returns unsuccessfully.

PROGRAM

Execute a program to determine whether there is a match; the key is true if the program returns successfully. The device properties are made available to the executed program in the environment. The program's standard output is available in the RESULT key.

This can only be used for very short-running foreground tasks. For details, see RUN.

source: man udev

  1. Add new rules file

    /etc/udev/rules.d/90-prevent-auto-mount.rules

    ACTION=="add", KERNEL="sd[a-z][0-9]*", DRIVERS=="usb-storage", PROGRAM="/usr/bin/pgrep yourprogramname", ENV{UDISKS_IGNORE}="1"
    
  2. Reload rules

    sudo control --reload-rules
    

BTW, udisk2 is the one responsible for auto-mounting