Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  20] [ 0]  / answers: 1 / hits: 27353  / 1 Year ago, sun, february 26, 2023, 6:01:48

What can I do to run automatically a script after I mount/plugin or unmount/unplug a USB device?


More From » usb

 Answers
1

Thanks to MinimusHeximus and the respective contributors to the thread he mentioned in his comment to my similar question, I think I can now offer you the following answer.


You'll need 5 (five) files for such a USB device as follows, simply filling in respective values <fortheseparts>:


/etc/udev/rules.d/00-usb-<yourdevice>.rules


ACTION=="add", ATTRS{idVendor}=="<yourvendorid>", ATTRS{idProduct}=="<yourproductid>", ENV{XAUTHORITY}="/home/<user>/.Xauthority", ENV{DISPLAY}=":0", OWNER="<user>", RUN+="/usr/local/bin/usb-<yourdevice>-in_udev"    
ACTION=="remove", ATTRS{idVendor}=="<yourvendorid>", ATTRS{idProduct}=="<yourproductid>", ENV{XAUTHORITY}="/home/<user>/.Xauthority", ENV{DISPLAY}=":0", OWNER="<user>", RUN+="/usr/local/bin/usb-<yourdevice>-out_udev"

/usr/local/bin/usb-<yourdevice>-in_udev


#!/bin/bash
/usr/local/bin/usb-<yourdevice>-in &

/usr/local/bin/usb-<yourdevice>-in


#!/bin/bash
sleep 1
<yourbashscriptcode>

/usr/local/bin/usb-<yourdevice>-out_udev


#!/bin/bash
/usr/local/bin/usb-<yourdevice>-out &

/usr/local/bin/usb-<yourdevice>-out


#!/bin/bash
sleep 1
<yourbashscriptcode>

Notes:



  1. You can capture the values <yourvendorid> and <yourproductid> by entering the command lsusb in Terminal -- when your USB device is plugged in -- which will list all your USB devices currently available, like Bus 003 Device 002: ID 8087:07da Intel Corp., where 8087 is the VendorID and 07da is the ProductID.



  2. And <yourdevice> can be any arbitrary name you may choose for your USB device, for example, I chose to use the generic name "keyboard" when creating such files for my USB keyboard which required applying a different keyboard layout whenever it's plugged in.



  3. In some scenarios, it may not be necessary to use the ACTION=="remove" line in the udev rules file, and hence the associated 2 (two) "out" files, when you don't need to do anything (e.g. reverse a change made when the device is plugged in) after the device is plugged out.



  4. Some display managers store the .Xauthority outside the user home directory. You will need to update the ENV{XAUTHORITY} accordingly. As an example GNOME Display Manager looks as follows:


    $ printenv XAUTHORITY

    /run/user/1000/gdm/Xauthority



[#31661] Tuesday, February 28, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shadowoof

Total Points: 293
Total Questions: 112
Total Answers: 137

Location: Burkina Faso
Member since Sun, Nov 21, 2021
3 Years ago
;