$_ BSDHowTo.ch
How To... Why not..? Scripts RSS logo

How to generate UUIDs on OpenBSD

Last update: 2018-08-17

Introduction

When I created the Atom feed for this site I wanted to use UUIDs in the tags of the file. I looked for an easy way to generate a new UUID. So I wrote the shell script uuid.sh.

IDs in Atom feeds

According to section 4.2.6 of RFC 4287 the id must be generated once, be unique and must not change during the lifetime of the referenced element. The same RFC describes id elements as looking similar to the URI of the referenced element. This is not a must criteria. It is easier to use UUIDs for the id field in Atom feeds than complete URIs which must be escaped according to a list of rules.

Type of UUID

UUIDs are defined in RFC 4122. There are different versions using different ways to generate UUIDs for different purposes. For my purpose random UUID (version 4) fits best. It is also the most easy one to create and doesn’t require any user input or preexisting data like MAC address.

The script

The script generates random numbers and sets the required bits according to RFC 4122, then prints the UUID in the common format as string to stdout:

#!/bin/ksh
#
# $Header$

for i in $(jot -s " " - 0 7) ; do
    v[$i]=$(($RANDOM+$RANDOM))
done
v[3]=$((${v[3]}|16384))
v[3]=$((${v[3]}&20479))
v[4]=$((${v[4]}|32768))
v[4]=$((${v[4]}&49151))
printf "%x%x-%x-%x-%x-%x%x%x\n" ${v[0]} ${v[1]} ${v[2]} ${v[3]} ${v[4]} ${v[5]} ${v[6]} ${v[7]}