How can I check via shell command if a specific external disk is connected? (by label or device id)
To test whether a specific device is connected you can use
grep with the
-q option to search the output of
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
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.
/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:
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
findfs is made for this. You can search by :
findfs LABEL="Ubuntu" &>/dev/null
findfs UUID="f9035fce-b3a1-4aee-80ef-44e432b78fdb" &>/dev/null
findfs PARTLABEL="EFI system partition" &>/dev/null
findfs PARTUUID="85e66d2f-3709-4060-938e-ffe836433cc9" &>/dev/null
Searches are case sensitive. If multiple partitions match, only the last one is displayed.