14

I am trying to run a script whenever a pendrive is connected to my system. I followed this and this question and it is working, but there are still some problems.

This is my udev rules file:

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

And this is my script:

#!/bin/bash

env > /tmp/env.out cp -r /media/device-name/* ~/test/

I have two questions:

  1. Whenever I plug my USB device in, the script is executed because a file env.out is generated in /tmp, but the data from the USB device are not copied to the test directory.

    If I run the script manually, it works fine! Why?

  2. How can I make my rules file more general so that it will work for any USB device which is connected without knowing its ID?

My idea behind this is to copy all the data from any connected USB device to my computer automatically when it is connected.

Null pointer
  • 2,607

2 Answers2

10

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!

Null pointer
  • 2,607
0

Try replacing the tilde with the full path to your home directory. I don't know if this will work, but you say that the script works when you run it directly but when it's run automatically it doesn't: This makes me think that the problem might be to do with it being run by a different user when it's run automatically, and the tilde resolves to different values for different users.