I would like to learn udev rules. Here is what I do:
victor@X301A1:~$ ls /etc/udev/rules.d/
70-persistent-cd.rules 70-persistent-net.rules READMEThen:
victor@X301A1:~$ sudo gedit /etc/udev/rules.d/01-my-first-udev.rulesMy rule:
ACTION=="add", RUN+="echo HELLO ! > /home/victor/udev_test_log.txt"After saving the file:
sudo udevadm control --reload-rulesI expected that connecting an USB device would write in the file but nothing happens. Where am I wrong?
2 Answers
In RUN you must to put a path to a script. See man udev:
Add a program to the list of programs to be executed for a specific device. This can only be used for very short running tasks. Running an event process for a long period of time may block all further events for this or a dependent device. Long running tasks need to be immediately detached from the event process itself.
For examle, create a new script, let say hello.sh in /lib/udev with sudo -H gedit /lib/udev/hello.sh and put next lines inside:
#!/bin/bash
echo HELLO ! > /home/<username>/udev_test_log.txtChange <username> with your user name. Save the file, close it and make it executable with:
chmod +x /lib/udev/hello.shAdd a new rule in your /etc/udev/rules.d/01-my-first-udev.rules file like this:
ACTION=="add", RUN+="/lib/udev/hello.sh" 2 Actually, I couldn't get a reference for this; But It's something got by Try & Error.
udevrequires the full path of script/program/file used either inPROGRAM,TEST,RUNorIMPORT.udevdoesn't support redirection operations.udevcan handle command with arguments.udevhas variable substitution.
So you can write multifunction script (not just blind/single task script :) ), Example that sure it works for me:
KERNEL=="2-1.2:1.[0-9]*", DRIVER!="usb-storage", RUN+="/bin/sh -c 'echo -n %k,%p > /home/sneetsher/Desktop/%n.txt'"/bin/shabsolute path>redirection is handled inside shell-c '...'2 command arguments%k,%p,%nudev variables (device kernel name, device path, device number)
So for your case:
ACTION=="add", RUN+="/bin/sh -c 'echo HELLO ! > /home/victor/udev_test_log.txt'"