Maximilian Maximilian - 4 months ago 46
Bash Question

Check if string is UUID bash

I am trying to test whether a string

$uuid
is a UUID. I have wrote 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

Answer

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-Z0-9a-z]{8}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{12}\}?$ ]]; then
    echo "true"
else
    echo "false"
fi

Notice the addition of a-z in each character class. This 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 been replaced with [A-Z0-9a-z].