Bash – How to create a UUID in bash

bashuuid

In Java it is possible to create a random UUID:

UUID uuid = UUID.randomUUID();

How to do this in Bash?

Best Answer

See the uuidgen program which is part of the e2fsprogs package.

According to this, libuuid is now part of util-linux and the inclusion in e2fsprogs is being phased out. However, on new Ubuntu systems, uuidgen is now in the uuid-runtime package.

To create a uuid and save it in a variable:

uuid=$(uuidgen)

On my Ubuntu system, the alpha characters are output as lower case and on my OS X system, they are output as upper case (thanks to David for pointing this out in a comment).

To switch to all upper case (after generating it as above):

uuid=${uuid^^}

To switch to all lower case:

uuid=${uuid,,}

If, for example, you have two UUIDs and you want to compare them in Bash, ignoring their case, you can do a tolower() style comparison like this:

if [[ ${uuid1,,} == ${uuid2,,} ]]