'Linux command to generate new GUID?

Sometimes in bash scripting, i need to generate new GUID(Global Unique Identifier).

I already done that by a simple python script that generates a new guid: see here

#! /usr/bin/env python
import uuid
print str(uuid.uuid1())

But i need to copy this script into any new system that i works on.

My question is: can anybody introduce a command or package that contains similar command ?



Solution 1:[1]

Assuming you don't have uuidgen, you don't need a script:

$ python -c 'import uuid; print(str(uuid.uuid4()))'
b7fedc9e-7f96-11e3-b431-f0def1223c18

Solution 2:[2]

You can use command uuidgen. Simply executing uuidgen will give you time-based UUID:

$ uuidgen
18b6f21d-86d0-486e-a2d8-09871e97714e

Solution 3:[3]

Since you wanted a random UUID, you want to use Type 4 instead of Type 1:

python -c 'import uuid; print str(uuid.uuid4())'

This Wikipedia article explains the different types of UUIDs. You want "Type 4 (Random)".

I wrote a little Bash function using Python to generate an arbitrary number of Type 4 UUIDs in bulk:

# uuid [count]
#
# Generate type 4 (random) UUID, or [count] type 4 UUIDs.
function uuid()
{
    local count=1
    if [[ ! -z "$1" ]]; then
        if [[ "$1" =~ [^0-9] ]]; then
            echo "Usage: $FUNCNAME [count]" >&2
            return 1
        fi

        count="$1"
    fi

    python -c 'import uuid; print("\n".join([str(uuid.uuid4()).upper() for x in range('"$count"')]))'
}

If you prefer lowercase, change:

python -c 'import uuid; print("\n".join([str(uuid.uuid4()).upper() for x in range('"$count"')]))'

To:

python -c 'import uuid; print("\n".join([str(uuid.uuid4()) for x in range('"$count"')]))'

Solution 4:[4]

cat /proc/sys/kernel/random/uuid

Solution 5:[5]

In Python 3, no cast to str is required:

python -c 'import uuid; print(uuid.uuid4())'

Solution 6:[6]

If you just want to generate a pseudo-random string with some dashes at locations 8, 12, 16, and 20, you can use apg.

apg -a 1 -M nl -m32 -n 1 -E ghijklmnopqrstuvwxyz | \
    sed -r -e 's/^.{20}/&-/' | sed -r -e 's/^.{16}/&-/' | \
    sed -r -e 's/^.{12}/&-/' | sed -r -e 's/^.{8}/&-/'

The apg clause generates 32 symbols from [0-9a-f] (lower-case). The series of sed commands add the - tokens and can very likely be shortened.

Note that often an UUID has a particular format:

xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx

Here M and N fields encode the version/format of the UUID.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jossef Harush Kadouri
Solution 2 Azatik1000
Solution 3 Will
Solution 4
Solution 5 jamesc
Solution 6 Anne van Rossum