9

How can I check via shell command if a specific external disk is connected? (by label or device id)

9

To test whether a specific device is connected you can use grep with the -q option to search the output of lsusb or lsblk, e.g.

uuid=f9035fce-b3a1-4aee-80ef-44e432b78fdb
lsblk -f | grep -wq $uuid && echo yes || echo no

devicename="some Inc. Keyboard"
lsusb | grep -q "$devicename" && echo yes || echo no

or with if:

uuid=f9035fce-b3a1-4aee-80ef-44e432b78fdb
if lsblk -f | grep -wq $uuid; then
  echo yes
else
  echo no
fi

Both can be used no matter whether the device is mounted.

  • For mounted partitions - lsblk -f | grep f9035fce-b3a1-4aee-80ef-44e432b78fdb | grep / -q && echo yes || echo no . – N0rbert Nov 20 '17 at 10:33
  • Of course, I used UUID which you provided :) – N0rbert Nov 20 '17 at 10:35
8

/dev/disk/ contains the following directories, which contain symbolic link to real devices. This links are dynamically created and removed by udev, so they're a are always up-to-date:

  • by-id
  • by-partlabel
  • by-partuuid
  • by-path
  • by-uuid

So checking for the existence of the symlink will use less resources.

Here is an example testing the presence of a disk using its serial number:

test -e /dev/disk/by-id/wwn-0x5002538d408be9e0 && echo yes || echo no

In my backup script I even don't check the disk presence, I only check the result of the mount command like this:

mount -o noatime $DESTINATION_PARTITION $DESTINATION_DIR || exit 1
2

lsusb for listing connected usb device if your external disk is connected through USB interface.

lsblk -f to list block devices, UUIDs and their mount-points as your external disk is a block device.

  • 1
    @N0rbert why do you need -f to list mount points? The default output lists them anyway – muru Nov 20 '17 at 10:27
0

findfs is made for this. You can search by :

  • FS label

    findfs LABEL="Ubuntu" &>/dev/null
    
  • FS uuid

    findfs UUID="f9035fce-b3a1-4aee-80ef-44e432b78fdb" &>/dev/null
    
  • GPT label

    findfs PARTLABEL="EFI system partition" &>/dev/null
    
  • GPT uuid

    findfs PARTUUID="85e66d2f-3709-4060-938e-ffe836433cc9" &>/dev/null
    

Searches are case sensitive. If multiple partitions match, only the last one is displayed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.