Linux console - programmatical detection of which device a USB storage is assigned to

Solution 1:

the by-id entry is a link, in most cases you can simply use that instead of /dev/sdc1. if not, you can dereference it with readlink

readlink -f /dev/disk/by-id/usb-Freecom_ToughDrive_1A90102657FF-part1
/dev/sdc1

Solution 2:

You can fix is easily with udev rules. udev rules run on boot and at various hot-plug events to run special handling programs / services or set device naming. It sounds like what you want a udev rule to to consistently name your drive to something like /dev/backup so an mtab entry can consistently mount /dev/backup to /mnt/backup (you can even have the device mounted automatically if you'd like.

Here is an older but still largely relevant guide to writing udev rules. In recent Linux distros udevinfo functionallity has been folded into the udevadm command. Using a command like this should help you figure out what particular fields you want to match on:

udevadm info -q all --path=/sys/block/sdc

Once you know what fields are sufficient for mapping, you'll want to create a udev rule file in /etc/udev/rules.d/ (noting that rule files are evaluated in natural sort order and your distribution may have it's own rules stored somewhere such as /lib/udev/rules.d/ so name accordingly). You'll want to create a rule that looks something like this which will create a /dev/backup symlink pointing to whatever the device is named:

ENV{DEVTYPE}=="disk", ID_SERIAL=="Freecom_ToughDrive_1A90102657FF", SYMLINK+="backup"
ENV{DEVTYPE}=="partition", ID_SERIAL=="Freecom_ToughDrive_1A90102657FF", SYMLINK+="backup%n"

Note: I'm guessing the serial number above based on the /dev/disk/by-id/ you list above. This may not be matching on the right field or the right value. Further note that this is matching a specific serial number and therefore a specific device, you'll need to change this if you change devices.

Hope that helps!

Simple approach: Since I use udev all the time to polish products for customer consumption, it's often the first thing I reach for. udev is already doing what you want by creating the device unique /dev/disk/by-id entries. Just change your /etc/mtab to mount /dev/disk/by-id/Freecom_ToughDrive_1A90102657FF-part1 at /mnt/backup. A mount /mnt/backup in your script will suffice for the mount.