Write files in usb when connect by /etc/udev/rules.d/

Solution 1:

  • What works for me, adding delay (sleep) and disown the script that has delay using an intermediate script.

    RUN{type}

    ...
           This can only be used for very short-running foreground tasks.
           Running an event process for a long period of time may block all
           further events for this or a dependent device.
    
           Starting daemons or other long running processes is not appropriate
           for udev; the forked processes, detached or not, will be
           unconditionally killed after the event handling has finished.
    

    source: man udev

  • There a similar case here: Why do my udev rules run if I use udevadm trigger, but NOT at boot time?. Fëamarto's answer seems better than my solution here. It waits till its file system is ready in rw mode. You may give it a try.

    Because this is a USB drive, it can be removed before mounting. The script will stay alive till next reboot or it get plugged again (which trigger another instance) and mounted.

    One way to fix that is to check if related /dev/sdxY still exists. on each cycle.

  • Here is my setup:

    1. /etc/udev/rules.d/99-sneetsher-tests.rules

      ACTION=="add", ENV{ID_FS_UUID}=="6664-B2DA", RUN+="/usr/bin/sudo -u user /home/user/mycrazy.sh"
      
    2. /home/user/mycrazy.sh

      #!/bin/sh
      
      /home/user/mycrazy2.sh & disown
      
    3. /home/user/mycrazy2.sh

      #!/bin/sh
      
      PATH_USB=/media/user/MYFLASH3
      sleep 5
      mkdir $PATH_USB/some_folder