Running a script when connecting a USB device

To answer my own question:

1. The script was not running because it needed sudo rights to run.

To solve this, make this script sudo executable:

  • Edit the sudoers file using:

    sudo visudo
    
  • After line 25 (i.e %sudo ALL=(ALL)) add this:

    username  ALL=(ALL) NOPASSWD: /home/username/my_script.sh
    

Now we can use sudo in this script without being asked for the sudo password. However, this may cause some security problems, so please refer to this question: How do I sudo a command in a script without being asked for a password?

2. Answer to my second question:

To make this script work for any USB device which is connected, change the udev rules file's content to this:

ACTION=="add", ATTRS{idVendor}=="`****`", ATTRS{idProduct}=="`****`", RUN+="/usr/local/my_script.sh"

The asterik (*) tells that this should be done for every USB device connected.

That's it! Make sure that script is executable and plug your USB in!

ENjoy!