Sunday, July 29, 2012

script that automatically mount flash disk and execute commands on plugged in (插入优盘自动挂载并执行命令)

Tags: udev, UUID.

1 Find out unique ID of the flash disk for udev :
$ udevadm info -a -p  $(udevadm info -q path -n /dev/sdc) |grep  serial
Here is the output:
(change /dev/sdc for your condition)

2 create udev rules
$ sudo vim /etc/udev/rules.d/81-sandisk.rules
Put the following in this file :
KERNEL=="sd*", ATTRS{serial}=="2004290613079860C679", SYMLINK+="sandisk", RUN+="/bin/bash /home/j/script/"

3 Find out the unique ID of the flash disk for linux filesystem
ls /dev/disk/by-uuid/
Here is one of the output:
48DD-2448 -> ../../sdc1

4 Create a script
$ cd ~/script/ (note this path must be in $PATH)
$ vim
Put the following into the script:
device=`ls /dev/disk/by-uuid/48DD-2448 -l | awk -F/ '{print $NF}'`  #assign a variable to $device, because the location of flash disk changes often, sometimes /dev/sdb, sometimes /dev/sdc...
sudo mount -t vfat /dev/$device /mnt/sandisk/ # mount the flash disk
# add your stuff below, ie, tar /etc/ ~/ and mv to the flash disk
# script END
4.1 $ sudo chmod +x

5 Point:
5.1 what? mount and execute commands as flash disk be blugged in
5.2 why? udev and filesystem both has it's unique id for a special disk, that makes sense
5.3 connection between UUID and udev is possible :)
5.4 this script will work only on THE flash disk, because udev attrs serial and uuid are UNIQUE

Have Fun!

1 udev
2 uuid