11

I would like to define a Bash variable PART_ID as being equal to the UUID of the /dev/sdb1 partition. The closest I have gotten to the desired answer is the output of:

ls -ld /dev/disk/by-uuid/* | grep sdb1

which, for me, gives:

lrwxrwxrwx 1 root root 10 Mar 16 17:02 /dev/disk/by-uuid/d26c3e60-0cfb-4118-9dec-1f1819439790 -> ../../sdb1

which is not an acceptable value for me to set PART_ID to. Rather what PART_ID should equal is d26c3e60-0cfb-4118-9dec-1f1819439790.

1
  • This has been asked before, seach... my_uuid=$(lsblk /dev/sdb1 -no UUID) Commented Mar 16, 2016 at 14:38

3 Answers 3

21

Note that's the UUID of the filesystem (or other structured data with a UUID the udev scripts know about) on the partition, not the UUID of the partition itself (not all partitioning schemes give UUIDs to partition anyway). See also Difference between UUID from blkid and mdadm?.

A few options on Linux-based systems to get the FS UUID:

fs_uuid=$(blkid -o value -s UUID /dev/sdb1)
fs_uuid=$(lsblk -no UUID /dev/sdb1)
fs_uuid=$(udevadm info -n sdb1 -q property | sed -n 's/^ID_FS_UUID=//p')
fs_uuid=$(find /dev/disk/by-uuid -lname '*/sdb1' -printf %f)

The first one may require superuser privileges or at least the right to read the device.

If the filesystem is mounted, you can also use:

fs_uuid=$(findmnt -fn -o UUID /dev/sdb1)
3
  • Just a follow-up. other than udevadm and find commands, superuser privilege is required for blkid, lsblk, and findmnt command. Commented Nov 15, 2018 at 20:15
  • fs_uuid=$(lsblk -ndo UUID /dev/sdb1) (with the additional -d flag) may be more effective if /dev/sdb1 has descendants, as can be the case if used in a RAID, LVM, or as an encrypted partition. Commented Jul 23, 2019 at 18:39
  • If you're using busybox then blkid -o value -s UUID /dev/sdb1 won't work. It seems to ignore all flags. So if you're on alpine install blkid via apk add blkid, and then run the command.
    – silverduck
    Commented Jan 17, 2023 at 3:02
6

You can do it in this way

PART_ID=$(blkid -o value -s UUID /dev/sdb1)

0
1

Putting it all together (thank you, @Mongrel!):

This will automagically get the

DISK=$(mount | grep " $1 type" | awk '{print $1}')
PART_UUID=$(blkid -o value -s UUID ${DISK})
echo "DISK UUID ($1): ${PART_UUID}"

Output:

DISK UUID (/): cf9eb16f-c1fa-45d1-9764-b10f064cc993

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .