On linux, you can’t count on the devices listed under /dev/sd*
or /dev/xvd*
, to have the same names or order. With the UUID (which is how /etc/fstab
usually specifies how to mount the root system device), the /dev
device name can be determined using the blkid
command and some hacky bash.
# For a system that uses /dev/sda, etc. use 0:8 string slice for blkid
MYDEVICE=$(blkid | grep ${MYUUID}) ; echo ${MYDEVICE:0:8} # /dev/sdc
However, you might need to do something like start a Docker container with your main system device connected using docker run --device=...
, and so the following also works in this specific case looking for the device mounted at the local machine’s /
.
# For a system that uses /dev/sd*, etc. use 2:3 string slice for lsblk
MYDEVICE=$(lsblk -f | grep -v loop | grep " /$") ; echo /dev/${MYDEVICE:2:3} # /dev/sdc
In addition to the device names and mount points, lsblk
provides the associated UUIDs as well.
# Grep UUID
MYDEVICE=$(lsblk -f | grep -v loop | grep "${MYUUID}") ; echo /dev/${MYDEVICE:2:3}
# Another Mounted Device
MYDEVICE=$(lsblk -f | grep -v loop | grep " /some/other/mount/point") ; echo /dev/${MYDEVICE:2:3}
You can even skip the bash var string slicing thing entirely with cut
:
echo /dev/$(lsblk -f | grep -v loop | grep "${MYUUID}" | cut -c 7-9)