Skip to main content

How to Generate UUID in Bash

Complete shell script guide with multiple methods

Most Linux and macOS systems already have everything you need to generate a UUID, with no package installation required. The uuidgen command — built into util-linux on Linux and libuuid on macOS — prints a random UUID to your terminal in a single call, and you can capture it straight into a shell variable for scripts, log tags, or temporary filenames. Below you'll find copy-paste ready commands for generating a UUID in Bash, validating a UUID string with a regex pattern, and the alternate flags uuidgen supports for forcing a specific version. The guide to uuid in rust includes serde derive macros, MessagePack serialization, and config file usage patterns.

Generate UUID in Bash

$ uuidgen
550e8400-e29b-41d4-a716-446655440000

How to Generate a UUID in Bash

The standard way to generate a UUID in Bash is the uuidgen command, pre-installed on macOS (part of libuuid) and most Linux distributions (part of util-linux). Call it directly or capture the output in a variable for use elsewhere in your script. The r uuid reference explains how to use uuid::UUIDgenerate() for random v4 identifiers in R.

generate.sh
#!/bin/bash

my_uuid=$(uuidgen)
echo "$my_uuid"
# Output: 550E8400-E29B-41D4-A716-446655440000

# Normalize to lowercase (uuidgen prints uppercase on macOS, lowercase on most Linux)
echo "$my_uuid" | tr '[:upper:]' '[:lower:]'

Explanation

Validate a UUID String in Bash

Bash has no typed UUID value, so validating a UUID string means checking that it matches the expected shape with a regular expression. The [[ ... =~ ... ]] conditional performs the match without spawning an external process. For idiomatic Kotlin UUID patterns with extension functions and sealed classes, see the kotlin uuid guide.

validate.sh
#!/bin/bash

id="550e8400-e29b-41d4-a716-446655440000"
pattern='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'

if [[ "$id" =~ $pattern ]]; then
    echo "valid"
else
    echo "invalid"
fi

Explanation

Other Options for Generating UUIDs in Bash

uuidgen also accepts flags for forcing a specific UUID version, and Linux offers a kernel-level fallback for systems where uuidgen isn't installed.

alternatives.sh
#!/bin/bash

# Force a random (version 4) UUID
uuidgen -r

# Force a time-based (version 1) UUID
uuidgen -t

# Kernel-level fallback on Linux -- no package required
cat /proc/sys/kernel/random/uuid

Explanation

Comments & Feedback

Share your experience or ask questions about this tool

Copied!