Bash script to detect when my USB is plugged in and to then sync it with a Directory
Asked Answered
T

4

18

Is there a Bash script and/or daemon that I can write that will detect a specific USB drive and then sync that drive with a directory?

Tetherball answered 15/11, 2010 at 22:15 Comment(0)
E
24

For future reference, here's how to run a bash script upon detection of a USB drive.

Connect your device and run lsusb to retrieve the device's info. You should see something similar to this:

$ lsusb
Bus 002 Device 039: ID 0bc2:2100 Seagate RSS LLC

In this case, the vendor ID of the device is 0bc2 and the product ID is 2100.

Now you can create your UDEV rule using a text editor of your choice.

$sudo vi /etc/udev/rules.d/85-my_usb_device_rule.rules

And add this:

ACTION=="add", SUBSYSTEM=="usb", SYSFS{idVendor}=="0bc2", SYSFS{idProduct}=="2100", RUN+="/home/myhome/my_script"

/home/myhome/my_script is the path to your script which it would do whatever you want.

To make sure the detection script will execute right away, run this command to reload the UDEV rules:

$sudo udevadm control --reload-rules

This was tested on Fedora 14.

Evanthe answered 16/11, 2011 at 0:53 Comment(1)
I used this with Crunchbang Linux 11(waldorf)[debian based], but I had to change 'SYSFS' to 'ATTR' to get it to work. This guy posted a good method of debugging udev... jpichon.net/blog/2011/12/debugging-udev-rulesDiencephalon
O
7

I didn't do it myself, but you can try udev rules like this:

# Hitachi SimpleDrive mini, model HTS545050B9A300 (500 GB USB HDD)
SUBSYSTEM=="block", ATTR{size}=="976768002", ATTRS{product}=="SimpleDrive mini", ATTRS{serial}=="2512009121920487", ACTION=="add", RUN+="/lib/udev/local.usb.hdd.sh add $devpath"

Place it in /etc/udev/rules.d/90-local.rules or similar place, certainly dependable on your OS.

Oskar answered 15/11, 2010 at 22:23 Comment(3)
Is it possible to use UUID and do away with all the rest of those attributes?Claudieclaudina
sorry, i don't know -- this is on my own todo list yet :)Oskar
Hi. It works. Thanks. What about when it is plugged out? Changing "add" to "remove" didn't help.Oysterman
S
3

Here is an example python deamon that you could use for the listening part, then copying the files to your directory shouldn't be a problem.

Scandal answered 15/11, 2010 at 22:32 Comment(1)
Try to refrain from using external link because that external link may expire.Etheridge
A
0

There are excellent answers here already but depending on your use case, it could be as simple as
[ -d /run/media/$USER/USB_STICK ] && do_stuff

USB_STICK here is the label of the usb stick.

Anisometric answered 4/8, 2022 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.