2

I'm working with Raspberry Pi. Previously, I used udev rule to run a script when a usb flash memory was plugged. The following was the content of /etc/udev/rules.d/10-usbstick.rules file:

ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd[a-z]1" SYMLINK+="usbflash", RUN+="/path/to/myhup.sh"

And then in myhup.sh :

#!/bin/sh
nohup /path/to/myscript.sh

This method worked fine. When a usb flash memory was plugged, it automatically started to run the myscript.sh file.

However, after upgrading to Jessie, it doesn't work. When plugging a usb flash memory, it gives the following errors:

[ 2026.652130] sd 0:0:0:0: [sda] No Caching mode page found
[ 2026.652238] sd 0:0:0:0: [sda] Assuming drive cache: write through
[ 2029.532163] ntfs: (device sda1): check_mft_mirror(): $MFT and $MFTMirr (record 0) do not match.  Run ntfsfix or chkdsk.
[ 2029.532355] ntfs: (device sda1): load_system_files(): $MFTMirr does not match $MFT.  Mounting read-only.  Run ntfsfix and/or chkdsk.

I decided to use systemd service method. So I changed the udev rule to:

ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd[a-z]1" SYMLINK+="usbflash", RUN+="systemctl start myusb.service"

And created the myusb.service with the following content:

[Unit]
Description=run myscript
[Service]
Type=oneshot
ExecStart=/path/to/myscript.sh
[Install]
WantedBy=multi-user.target

And then:

sudo chmod 644 /lib/systemd/system/myusb.service
sudo systemctl daemon-reload
sudo systemctl enable myusb.service
sudo reboot

This time, it didn't work again, and gave the following errors:

[ 2026.652130] sd 0:0:0:0: [sda] No Caching mode page found
[ 2026.652238] sd 0:0:0:0: [sda] Assuming drive cache: write through

So, how can I run a script automatically when a usb flash memory is plugged (in Jessie)?

1

If you want to run a systemd unit from your udev, you can now just name the unit (see man systemd.device). For example, if you look in your (/usr)/lib/udev/rules.d/99-systemd.rules you should find an example like

SUBSYSTEM=="bluetooth", TAG+="systemd", ENV{SYSTEMD_WANTS}+="bluetooth.target"

which has the 2 important points: you must add the TAG systemd, and you must set the SYSTEMD_WANTS to the (base) name of your unit. If no rules use SYSTEMD_WANTS, then your version does probably not yet support this feature.

So in your case we have

ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd[a-z]1", SYMLINK+="usbflash", TAG+="systemd", ENV{SYSTEMD_WANTS}+="myusb.service"

Note, you had a comma missing in udev rule. Note, the 2 errors you list for [sda] are just informational, and not a problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.