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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With