Check if specific external disk is connected

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


/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

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.


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.