-3

I need to run a Python or a shell script whenever a USB is plugged in.

So I need to create a udev rule for that.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abhishek
  • 11
  • 2
  • 1
    Sure, go ahead! What prevents you from doing that? Maybe check [ask] and look for some tutorials or the udev documentation. – Robert Sep 08 '22 at 16:41
  • Stack Exchange site *[Unix & Linux](https://unix.stackexchange.com/tour)* happily accepts such work orders. No questions asked. – Peter Mortensen May 15 '23 at 14:36
  • In any case, this is very likely a duplicate. Where is the canonical question? – Peter Mortensen May 15 '23 at 14:36
  • Some starting points (not canonical; low scored): *[Run script with udev after USB plugged in on a Raspberry Pi](https://stackoverflow.com/questions/34295198/)*, *[Cannot run an application from udev script](https://stackoverflow.com/questions/43391115)*, and *[Play music from a Bash script running from 'udev'](https://stackoverflow.com/questions/63620745)*. – Peter Mortensen May 15 '23 at 14:47
  • [297 candidates](https://stackoverflow.com/search?q=udev+run+script) – Peter Mortensen May 15 '23 at 14:53

1 Answers1

1

You can add a udev rules file. For example, you can add the file /etc/udev/rules.d/99-local.rules:

Its content can be:

KERNEL=="sd*", SUBSYSTEMS=="block", ACTION=="add", RUN+="/bin/systemctl start usb-mount@%k.service"

KERNEL=="sd*", SUBSYSTEMS=="block", ACTION=="remove", RUN+="/bin/systemctl stop usb-mount@%k.service"

The previous is a udev rules file that starts and stops the systemd service usb-mount@.service by systemctl. By this service file you can start the desired Python or Bash script.

A content example for the service file is the following:

[Unit]
Description=Mount USB Drive on %i

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/usr/bin/usb-mount.sh add %i
ExecStop=/usr/bin/usb-mount.sh remove %i

Inside the unit file you can find the options ExecStart and ExecStop that start the Bash script /usr/bin/usb-mount.sh. The script accepts two arguments:

  1. add | remove
  2. the name of the USB device file (sda, sdb, sdb1, and so on).

So usb-mount.sh is called when you insert (ACTION==add in the udev rule) or remove (ACTION==remove in the udev rule) a USB storage device.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
frankfalse
  • 1,553
  • 1
  • 4
  • 17