17

I want to filter the output of the blkid to get the UUID.

The output of blkid looks like

CASE 1:-

$ blkid
/dev/sda2: LABEL="A" UUID="4CC9-0015"
/dev/sda3: LABEL="B" UUID="70CF-169F"
/dev/sda1: LABEL=" NTFS_partition" UUID="3830C24D30C21234"

In somecases the output of blkid looks like

CASE 2:-

$ blkid
/dev/sda1: UUID="d7ec380e-2521-4fe5-bd8e-b7c02ce41601" TYPE="ext4" 
/dev/sda2: UUID="fc54f19a-8ec7-418b-8eca-fbc1af34e57f" TYPE="ext4" 
/dev/sda3: UUID="6f218da5-3ba3-4647-a44d-a7be19a64e7a" TYPE="swap" 

I want to filter out the UUID.

Using the combination of grep and cut it can be done as

/sbin/blkid | /bin/grep 'sda1' | /bin/grep -o -E 'UUID="[a-zA-Z|0-9|\-]*' | /bin/cut -c 7-

I have tried using awk , grep and cut as below for filtering the UUID

$ /sbin/blkid | /bin/grep 'sda1' | /usr/bin/awk '{print $2}' | /bin/sed 's/\"//g' | cut -c 7-
7ec380e-2521-4fe5-bd8e-b7c02ce41601

The above command(which uses awk) is not reliable since sometimes an extra field such as LABEL may be present in the output of the blkid program as shown in the above output.

What is the best way to create a command using awk which works reliably? Please post if any other elegant method exits for the job using bin and core utils. I dont want to use perl or python since this has to be run on busybox.

NOTE:-I am using busybox blkid to which /dev/sda1 can not be passed as the args(the version i am using does not support it) hence the grep to filter the line.

UPDATE :- added the CASE 2: -output to show that field position can not be relied upon.

3
  • 2
    I do simply: sudo blkid | cut -d' ' -f2 | cut -d\" -f2 Nov 26, 2012 at 13:19
  • field positions can not be relied upon. sample out of the program is $ blkid /dev/sda2: LABEL="A" UUID="4CC9-0015" /dev/sda3: LABEL="B" UUID="70CF-169F" /dev/sda1: LABEL=" NTFS_partition" UUID="3830C24D30C21234" /usr/etc/udev/rules.d # blkid | cut -d' ' -f2 | cut -d\" -f2 A B Nov 26, 2012 at 13:26
  • 1
    check this: sudo blkid | grep -oP 'UUID=[0-9a-zA-Z"-]+' Nov 26, 2012 at 13:30

6 Answers 6

92

Why are you making it so complex?

Try this:

# blkid -s UUID -o value
d7ec380e-2521-4fe5-bd8e-b7c02ce41601
fc54f19a-8ec7-418b-8eca-fbc1af34e57f
6f218da5-3ba3-4647-a44d-a7be19a64e7a

Or this:

# blkid -s UUID -o value /dev/sda1
d7ec380e-2521-4fe5-bd8e-b7c02ce41601

Install proper blkid package if you don't have it:

sudo apt-get install util-linux
sudo yum install util-linux
2
  • Great! Better than using regex.
    – Zee
    Jan 21, 2015 at 15:31
  • 2
    looks great if you have a real blkid, but not on busybox's blkid -- thats why people are looking for parsing solutions Jan 29, 2016 at 13:36
6

For all the UUID's, you can do :

$ blkid | sed -n 's/.*UUID=\"\([^\"]*\)\".*/\1/p' 
d7ec380e-2521-4fe5-bd8e-b7c02ce41601
fc54f19a-8ec7-418b-8eca-fbc1af34e57f
6f218da5-3ba3-4647-a44d-a7be19a64e7a

Say, only for a specific sda1:

$ blkid | sed -n '/sda1/s/.*UUID=\"\([^\"]*\)\".*/\1/p' 
d7ec380e-2521-4fe5-bd8e-b7c02ce41601

The sed command tries to group the contents present within the double quotes after the UUID keyword, and replaces the entire line with the token.

2
  • 6
    Warning! This will yield INCORRECT UUID on GPT! On GPT, besides UUID there is also PARTUUID, so your regexp will match on that, as it is usually later on in the line. To fix, add a space before the "UUID". Also, to get an UUID for a specific drive, you don't need to parse it, just use blkid <device>
    – kralyk
    Apr 14, 2016 at 18:32
  • If you have labels on the devices (you should), you can filter by label, so if your volume is moved or mounted with another device id, you can always find the UUID: blkid -t LABEL=your-tag -s UUID -o value
    – Gabriel
    Jun 19, 2023 at 8:36
2

Here's a short awk solution:

blkid | awk 'BEGIN{FS="[=\"]"} {print $(NF-1)}'

Output:

4CC9-0015
70CF-169F
3830C24D30C21234

Explanation:

  • BEGIN{FS="[=\"]"} : Use = and " as delimiters
  • {print $(NF-1)}: NF stands of Number of Fields; here we print the 2nd to last field
  • This is based on the consistent structure of blkid output: UUID in quotes is at the end of each line.

Alternatively:

blkid | awk 'BEGIN{FS="="} {print $NF}' | sed 's/"//g'
1
  • Field postion can not be relied on, please look at the CASE 2:- output for which the solution does not work. Nov 27, 2012 at 8:26
0

data.txt

/dev/sda2: LABEL="A" UUID="4CC9-0015"
/dev/sda3: LABEL="B" UUID="70CF-169F"
/dev/sda1: LABEL=" NTFS_partition" UUID="3830C24D30C21234"

awk and sed combination

cat data.txt | awk 'BEGIN{FS="UUID";RS="\n"} {print $2}' | sed -e 's/=//'  -e 's/"//g'

Explanation:

  1. Set the Field Separator to the string 'UUID', $2 will give the rest output
  2. use sed then to remove the = and " as shown where -e is a switch so that you can give multiple sed commands/expression in one.
  3. All occurrences of " are removed using the ending g option i.e. global.
1
  • Field postion can not be relied on, please look at the CASE 2:- output for which the solution does not work. Nov 27, 2012 at 8:27
0

The question has a "e.t.c" so I'm going to assume python is one of the options ;)

#!/usr/bin/env python3

import subprocess, re, json

# get blkid output
blkid = subprocess.check_output(["blkid"]).decode('utf-8')


devices = []
for line in [x for x in blkid.split('\n') if x]:
        parameters = line.split()
        for idx, parameter in enumerate(parameters):
                if idx is 0:
                        devices.append({"DEVICE": re.sub(r':$','',parameter)})
                        continue

                key_and_value = parameter.split('=')
                devices[-1].update({
                        key_and_value[0]: re.sub(r'"','',key_and_value[1])
                })


uuids = [{dev['DEVICE']: dev['UUID']} for dev in devices if 'UUID' in dev.keys()]
print(json.dumps(uuids, indent=4, sort_keys=True))

Although, this is probably overkill and quite a few error handling/optimization is missing from this script XD

0

I assume you're using busybox in an initramfs and you are waiting for your e.g. USB drive with the rootfs on it to become available.

You could use the following awk script (busybox awk compliant).

# cat get-ruuid.awk 
BEGIN {
  ruuid=ENVIRON["RUUID"]
}

/^\/dev\/sd[a-z]/ {
  if (index($0, tolower(ruuid)) || index($0, toupper(ruuid))) {
    split($1, parts, ":")
    printf("%s\n", parts[1])
    exit(0) # Return success and stop further scanning.
  }
}

END {
  exit(1) # If we reach the end, it means RUUID was not found.
}

Call it as follows from e.g. the init script; this is not the most ideal way.

# The UUID of your root partition
export RUUID="<put proper uuid value here>"

for x in 1, 2, 3, 4, 5 ; do
  mdev -s
  found=$(blkid | awk -f ./get-ruuid.awk)
  test -z $found || break; # If no longer zero length, break the loop.
  sleep 1
done

But if this is the only reason why you would want to have an initramfs, I would use the 'root=PARTUUID=... waitroot' Linux kernel command line option. Check the kernel docs and sources.

Get the proper PARTUUID (NOT UUID) of your root partition with the blkid command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.