I was looking at libblkid and was confused about the documentation. Could someone provide me with an example of how I could find the UUID of a root linux partition using this library?
2 Answers
It's pretty much as simple as the manual makes it look: you create a probe structure, initialize it, ask it for some information, and then free it. And you can combine the first two steps into one. This is a working program:
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <blkid/blkid.h>
int main (int argc, char *argv[]) {
blkid_probe pr;
const char *uuid;
if (argc != 2) {
fprintf(stderr, "Usage: %s devname\n", argv[0]);
exit(1);
}
pr = blkid_new_probe_from_filename(argv[1]);
if (!pr) {
err(2, "Failed to open %s", argv[1]);
}
blkid_do_probe(pr);
blkid_probe_lookup_value(pr, "UUID", &uuid, NULL);
printf("UUID=%s\n", uuid);
blkid_free_probe(pr);
return 0;
}
blkid_probe_lookup_value
sets uuid
to point to a string that belongs to the pr
structure, which is why the argument is of type const char *
. If you needed to, you could copy it to a char *
that you manage on your own, but for just passing to printf
, that's not needed. The fourth argument to blkid_probe_lookup_value
lets you get the length of the returned value in case you need that as well. There are some subtle differences between blkid_do_probe
, blkid_do_safeprobe
, and blkid_do_fullprobe
, but in cases where the device has a known filesystem and you just want to pull the UUID out of it, taking the first result from blkid_do_probe
should do.

- 223,387
- 19
- 210
- 288
-
This example requires me to input the partition as an argument correct? How would I check the UUID of the ROOT partition? – HighLife Jul 25 '11 at 13:07
-
Define "the ROOT partition". The device mounted on `/` ? – hobbs Jul 25 '11 at 23:46
-
I've included
and have installed the necessary packages to use libblkid, but I'm still getting errors like blkid_somefuction was not declared in this scope. Am I forgetting something? – HighLife Jul 26 '11 at 13:28 -
use `/dev/root` as your partition – Vinicius Kamakura Jul 31 '11 at 15:12
-
is there any api to probe disk name and partition programmatically?? like from where to get "/dev/sda1" – Ravi Bhushan Aug 04 '15 at 12:56
-
Ps: `blkid_new_probe_from_filename` requires privileged (like root) access in case a libblkid cache does not exist. – Sdra Feb 09 '21 at 17:06
First you need to find the device mounted as as root. See man getmntent (3). Once you know the device, use blkid_new_probe_from_filename as described by hobbs.
#include <stdio.h>
#include <mntent.h>
int main() {
FILE* fstab = setmntent("/etc/mtab", "r");
struct mntent *e;
const char *devname = NULL;
while ((e = getmntent(fstab))) {
if (strcmp("/", e->mnt_dir) == 0) {
devname = e->mnt_fsname;
break;
}
}
printf("root devname is %s\n", devname);
endmntent(fstab);
return 0;
}

- 30,364
- 7
- 62
- 85
-
This is very helpful, I'm combining it with hobbs post and I'll see what happens. Thx – HighLife Jul 26 '11 at 13:29