Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate a random UUID in bash
#!/usr/bin/env bash
# Generate a pseudo UUID
uuid()
{
local N B C='89ab'
for (( N=0; N < 16; ++N ))
do
B=$(( $RANDOM%256 ))
case $N in
6)
printf '4%x' $(( B%16 ))
;;
8)
printf '%c%x' ${C:$RANDOM%${#C}:1} $(( B%16 ))
;;
3 | 5 | 7 | 9)
printf '%02x-' $B
;;
*)
printf '%02x' $B
;;
esac
done
echo
}
if [ "$BASH_SOURCE" == "$0" ]
then
uuid
fi
@dtwilliamson

This comment has been minimized.

Copy link

commented May 22, 2014

The T variable can be eliminated and the for T loop can be changed to:

    case $N in
        3 | 5 | 7 | 9)
            printf '-';;
    esac
@dtwilliamson

This comment has been minimized.

Copy link

commented May 22, 2014

Here is the whole thing restructured using only a case block (no ifs):

uuid()
{
    local N B C='89ab'

    for (( N=0; N < 16; ++N ))
    do
        B=$(( $RANDOM%256 ))

        case $N in
            6)
                printf '4%x' $(( B%16 ))
                ;;
            8)
                printf '%c%x' ${C:$RANDOM%${#C}:1} $(( B%16 ))
                ;;
            3 | 5 | 7 | 9)
                printf '%02x-' $B
                ;;
            *)
                printf '%02x' $B
                ;;
        esac
    done

    echo
}

Note that substring expansion introduces an arithmetic context so it's not necessary to use $(()) inside it. I moved the assignment of C outside the loop. Also, the values for the modulus operations are incorrect (15 should be 16 and 255 should be 256).

@markusfisch

This comment has been minimized.

Copy link
Owner Author

commented Jun 25, 2014

Sorry for the late reaction; didn't see your comment until now.

You're right! Updated the gist to your implementation. Thanks a lot!

@lowerpower

This comment has been minimized.

Copy link

commented Jul 21, 2016

if you need a crypto secure version using urandom:
https://github.com/lowerpower/UUID-with-bash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.