Check if specific external disk is connected

14,013

Solution 1

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.

Solution 2

/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

Solution 3

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.

Share:
14,013
Jeno
Author by

Jeno

Updated on September 18, 2022

Comments

  • Jeno
    Jeno almost 2 years

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

  • muru
    muru over 6 years
    @N0rbert why do you need -f to list mount points? The default output lists them anyway
  • N0rbert
    N0rbert over 6 years
    For mounted partitions - lsblk -f | grep f9035fce-b3a1-4aee-80ef-44e432b78fdb | grep / -q && echo yes || echo no .
  • N0rbert
    N0rbert over 6 years
    Of course, I used UUID which you provided :)