how i used udev, udevadm, and a shell script to automate syncing of media files between my android phone and computer

udev provides powerul rules that can be used to perform custom tasks whenever there is activity on usb ports. here's what i created in /etc/udev/rules.d/99-sync_music_files_on_android_devices.rules:

    
ACTION=="add|change", ATTR{size}=="31114240", ATTRS{vendor}=="SAMSUNG", ATTRS{model}=="GT-I9003", NAME="galaxy_s_external_sd", RUN+= "mkdir /media/galaxy_s_external_sd", RUN+="mount /dev/galaxy_s_external_sd /media/galaxy_s_external_sd", RUN+="/home/vinu/bin/sync_music_files_on_android_device.sh"
ACTION=="remove", RUN+="/bin/umount -l /media/galaxy_s_external_sd", RUN+="/bin/rmdir /media/galaxy_s_external_sd"   LABEL="sync_music_files_on_android_devices_end"

the first line registers an action to add/change event of a usb device that has attributes as size: 31114240 and parent device having attributes of vendor: "samsung" and so on. you can find the attributes related to your device by using udevadm as:

   $ udevadm info -q all -n /dev/{device_label}       

udevadm is pretty interesting and can provide a lot of information about devices, shows all applicable rules for a device, and also allows testing your rules using triggers. see the udevadm man page for details.

i've also asked the device label to be custom (NAME) as: galaxy_s_external_sd so that i can refer to it that way in RUN which creates a mount point and mounts the device at the desired location. then i RUN the shell script that actually syncs the media files and logs the activity:

#!/bin/bash
rsync -r -t -v --progress --delete-before /home/vinu/Music/sync /media/galaxy_s_external_sd/Music >> /home/vinu/log/rsync.log

interesting isn't it? let me know if you try this out, or if you've done more interesting stuff related to udev or, in general with linux, through comments.

references:

http://reactivated.net/writing_udev_rules.html

http://wiki.archlinux.org/index.php/Udev -- lots of examples