简体   繁体   中英

How do I write a script to identify and manipulate a specific drive in the terminal?

I'm trying to write a short script that can automatically unmount and remount a partition, without knowing where the drive is currently mounted.

The following command sort of works for me:

sudo umount /dev/sdX
sudo mount -t ntfs /dev/sdX /mnt/rec

The issue is, I'm running Linux live, and can't install it on my hard drive. As such, whenever I reboot the computer, /dev/sdX will sometimes mount as /dev/sdb, or /dev/sdd. As such, I can't just run a script to automatically mount the drive where I need to, without using

sudo fdisk -l

In order to verify what the drives are currently mounted as.

My question is: Is there a way to identify a drive, that's agnostic to where it's currently mounted?

Yes!

This was an annoying issue up until 2005 or so, but now can access devices based on device-independent identifiers thanks to udev .

Check out /dev/disk/ for all the various ways in which your partitions are automatically categorized independently of their /dev/sd* name:

$ find /dev/disk/
/dev/disk/by-uuid
/dev/disk/by-uuid/d7a395e4-e6fd-49bc-bbd9-af9c6a43211d
/dev/disk/by-partuuid
/dev/disk/by-partuuid/4434a42f-01
/dev/disk/by-path
/dev/disk/by-path/acpi-VMBUS:01-scsi-0:0:0:0-part1
/dev/disk/by-path/acpi-VMBUS:01-scsi-0:0:0:0
/dev/disk/by-path/pci-0000:00:07.1-ata-2
/dev/disk/by-id
/dev/disk/by-id/wwn-0x600224805c60e27d40a2d50b3961022c-part1
/dev/disk/by-id/scsi-3600224805c60e27d40a2d50b3961022c-part1
/dev/disk/by-id/wwn-0x600224805c60e27d40a2d50b3961022c
/dev/disk/by-id/scsi-3600224805c60e27d40a2d50b3961022c
/dev/disk/by-id/ata-Virtual_CD

These are all completely transparent symlinks to their backing device, so you can easily see what they correspond to:

$ ls -l /dev/disk/by-uuid/d7a395e4-e6fd-49bc-bbd9-af9c6a43211d
lrwxrwxrwx 1 root root 10 May 28 10:38 /dev/disk/by-uuid/d7a395[..]  -> ../../sda1

The by-uuid entries are generally your best bet, but partuuid and label may also be useful for less Linux-y file systems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM