Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is UUID

Tags:

bash

shell

uuid

I am trying to test whether a string $uuid is a UUID. I have written this script but for some reason it is not working:

uuid="7632f5ab-4bac-11e6-bcb7-0cc47a6c4dbd"
if [[ $uuid =~ ^\{?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}?$ ]]; then
    echo "true"
else
    echo "false"
fi
like image 355
maxisme Avatar asked Jul 16 '16 23:07

maxisme


2 Answers

Your regular expression doesn't accept lowercase letters as valid. Here is a fixed version:

#!/bin/bash
uuid="7632f5ab-4bac-11e6-bcb7-0cc47a6c4dbd"
if [[ $uuid =~ ^\{?[A-F0-9a-f]{8}-[A-F0-9a-f]{4}-[A-F0-9a-f]{4}-[A-F0-9a-f]{4}-[A-F0-9a-f]{12}\}?$ ]]; then
    echo "true"
else
    echo "false"
fi

First of all, you only really need to be searching A-F not A-Z because UUIDs contain hex digits.

Notice the addition of a-f in each character class. Your version will reject any UUID that is printed in lowercase. This new version works fine for me now. An alternative solution is to only use an uppercase UUID, instead of the lowercase one that you have. Your [A-Z0-9] classes have for those reasons been replaced with [A-F0-9a-f].

See the post by Ekeyme Mo for safety considerations.

like image 192
Spenser Truex Avatar answered Sep 21 '22 12:09

Spenser Truex


It is more safe to pre-save the pattern into a variable in bash =~ clause to avoid unpredictable escaping in bash.

uuid="7632f5ab-4bac-11e6-bcb7-0cc47a6c4dbd"
pattern='^\{?[A-Z0-9a-z]{8}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{12}\}?$'

if [[ "$uuid" =~ $pattern ]]; then
    echo "true" 
else
    echo "false" 
fi
like image 27
Ekeyme Mo Avatar answered Sep 18 '22 12:09

Ekeyme Mo