Method 1: uuidgen Command (Recommended)
The uuidgen utility is the standard tool for generating UUIDs on Linux/Unix systems:
#!/bin/bash
# Generate random UUID v4
uuidgen
# Output: 550e8400-e29b-41d4-a716-446655440000
# Generate UUID v1 (timestamp-based)
uuidgen -t
# Output: 6ba7b810-9dad-11d1-80b4-00c04fd430c8
# Generate UUID v4 (random) - explicit
uuidgen -r
# Store in variable
UUID=$(uuidgen)
echo "Generated UUID: $UUID"
# Uppercase output
uuidgen | tr 'a-z' 'A-Z'
# Output: 550E8400-E29B-41D4-A716-446655440000
# Lowercase output (default)
uuidgen | tr 'A-Z' 'a-z'
# Remove hyphens
uuidgen | tr -d '-'
# Output: 550e8400e29b41d4a716446655440000
# Generate multiple UUIDs
for i in {1..5}; do
uuidgen
done
Installation:
# Debian/Ubuntu
sudo apt install uuid-runtime
# RHEL/CentOS/Fedora
sudo yum install util-linux
# macOS (pre-installed)
uuidgen
Method 2: Linux Kernel Random (No Installation)
On Linux systems, read directly from the kernel's UUID generator (requires no additional packages):
#!/bin/bash
# Read UUID from Linux kernel
cat /proc/sys/kernel/random/uuid
# Output: 550e8400-e29b-41d4-a716-446655440000
# Store in variable
UUID=$(cat /proc/sys/kernel/random/uuid)
echo "UUID: $UUID"
# Generate multiple UUIDs
for i in {1..10}; do
cat /proc/sys/kernel/random/uuid
done
# Create array of UUIDs
declare -a uuids
for i in {1..5}; do
uuids+=("$(cat /proc/sys/kernel/random/uuid)")
done
# Print all UUIDs
printf '%s\n' "${uuids[@]}"
# Uppercase
cat /proc/sys/kernel/random/uuid | tr 'a-z' 'A-Z'
Advantage: No dependencies required on Linux systems. Fast and uses kernel-level randomness.
Method 3: Python One-liner
If Python is available, use it to generate UUIDs in Bash scripts:
#!/bin/bash
# UUID v4 (random)
python3 -c 'import uuid; print(uuid.uuid4())'
# UUID v1 (timestamp)
python3 -c 'import uuid; print(uuid.uuid1())'
# UUID v5 (SHA-1 hash)
python3 -c 'import uuid; print(uuid.uuid5(uuid.NAMESPACE_DNS, "example.com"))'
# Store in variable
UUID=$(python3 -c 'import uuid; print(uuid.uuid4())')
echo "Generated: $UUID"
# Uppercase
python3 -c 'import uuid; print(str(uuid.uuid4()).upper())'
# Generate multiple
for i in {1..5}; do
python3 -c 'import uuid; print(uuid.uuid4())'
done
# Check if Python is available
if command -v python3 &> /dev/null; then
UUID=$(python3 -c 'import uuid; print(uuid.uuid4())')
else
echo "Python not found"
fi
Method 4: Pure Bash Implementation
Generate UUID v4 using only Bash built-ins (no external dependencies):
#!/bin/bash
# UUID v4 generator function
generate_uuid() {
local N B T
for (( N=0; N < 16; ++N )); do
B=$(( RANDOM % 256 ))
if (( N == 6 )); then
printf '4%x' $(( B % 16 ))
elif (( N == 8 )); then
local C='89ab'
printf '%c%x' ${C:$(( RANDOM % ${#C} )):1} $(( B % 16 ))
else
printf '%02x' $B
fi
case $N in
3 | 5 | 7 | 9) printf '-' ;;
esac
done
echo
}
# Usage
UUID=$(generate_uuid)
echo "Generated UUID: $UUID"
# Generate multiple
for i in {1..5}; do
generate_uuid
done
Note: Uses $RANDOM which is less cryptographically secure than uuidgen or /proc/sys/kernel/random/uuid. Good for testing but prefer other methods for production.
Improved Pure Bash with /dev/urandom
More secure pure Bash implementation using /dev/urandom:
#!/bin/bash
generate_secure_uuid() {
local uuid
# Read 16 random bytes from /dev/urandom
local bytes=$(dd if=/dev/urandom bs=1 count=16 2>/dev/null | od -An -tx1 | tr -d ' \n')
# Format as UUID v4
uuid="${bytes:0:8}-${bytes:8:4}-4${bytes:13:3}-"
uuid+="$((0x${bytes:16:2} & 0x3f | 0x80))${bytes:18:2}-${bytes:20:12}"
echo "$uuid"
}
# Usage
UUID=$(generate_secure_uuid)
echo "Secure UUID: $UUID"
UUID Validation in Bash
Validate UUID format using regex pattern matching:
#!/bin/bash
# UUID validation function
is_valid_uuid() {
local uuid="$1"
local regex='^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
if [[ "$uuid" =~ $regex ]]; then
return 0 # Valid
else
return 1 # Invalid
fi
}
# Test validation
if is_valid_uuid "550e8400-e29b-41d4-a716-446655440000"; then
echo "Valid UUID"
else
echo "Invalid UUID"
fi
# Validate user input
read -p "Enter UUID: " user_uuid
if is_valid_uuid "$user_uuid"; then
echo "✓ Valid UUID format"
else
echo "✗ Invalid UUID format"
exit 1
fi
# Case-insensitive validation
is_valid_uuid_ci() {
local uuid=$(echo "$1" | tr 'A-Z' 'a-z')
is_valid_uuid "$uuid"
}
# Extract UUID version
get_uuid_version() {
local uuid="$1"
if is_valid_uuid "$uuid"; then
echo "${uuid:14:1}"
else
echo "Invalid UUID"
fi
}
UUID="550e8400-e29b-41d4-a716-446655440000"
echo "UUID version: $(get_uuid_version "$UUID")"
Bulk UUID Generation
Generate large numbers of UUIDs efficiently:
#!/bin/bash
# Generate N UUIDs and save to file
generate_bulk_uuids() {
local count=$1
local output_file=$2
for ((i=1; i<=count; i++)); do
uuidgen >> "$output_file"
done
echo "Generated $count UUIDs to $output_file"
}
# Usage
generate_bulk_uuids 1000 "uuids.txt"
# Faster parallel generation using xargs
seq 1000 | xargs -I{} -P 8 uuidgen > uuids.txt
# Generate with timestamps
generate_timestamped_uuids() {
local count=$1
for ((i=1; i<=count; i++)); do
echo "$(date -Iseconds),$(uuidgen)"
done
}
generate_timestamped_uuids 100 > timestamped_uuids.csv
# Generate unique filename using UUID
FILENAME="backup_$(uuidgen).tar.gz"
echo "Backup file: $FILENAME"
Practical Shell Script Examples
Real-world use cases for UUIDs in shell scripts:
Database Insert Script
#!/bin/bash
# Insert records with UUID primary keys
insert_user() {
local name=$1
local email=$2
local uuid=$(uuidgen)
psql -d mydb -c "
INSERT INTO users (id, name, email, created_at)
VALUES ('$uuid', '$name', '$email', NOW())
"
echo "Created user with ID: $uuid"
}
insert_user "John Doe" "john@example.com"
Unique Temporary Files
#!/bin/bash
# Create unique temporary file
TEMP_FILE="/tmp/temp_$(uuidgen).txt"
echo "Using temp file: $TEMP_FILE"
# Process data
echo "Processing..." > "$TEMP_FILE"
# Cleanup on exit
trap "rm -f $TEMP_FILE" EXIT
# Create unique log directory
LOG_DIR="/var/log/app_$(uuidgen)"
mkdir -p "$LOG_DIR"
Request ID for Logging
#!/bin/bash
# Generate request ID for distributed tracing
REQUEST_ID=$(uuidgen)
log_message() {
local level=$1
local message=$2
echo "[$(date -Iseconds)] [$REQUEST_ID] [$level] $message"
}
log_message "INFO" "Starting process"
log_message "DEBUG" "Processing data"
log_message "INFO" "Process completed"
Cross-Platform UUID Script
Detect and use the best available UUID method:
#!/bin/bash
# Cross-platform UUID generator
get_uuid() {
if command -v uuidgen &> /dev/null; then
# Use uuidgen if available
uuidgen
elif [ -f /proc/sys/kernel/random/uuid ]; then
# Use Linux kernel on Linux
cat /proc/sys/kernel/random/uuid
elif command -v python3 &> /dev/null; then
# Fall back to Python
python3 -c 'import uuid; print(uuid.uuid4())'
elif command -v python &> /dev/null; then
# Try Python 2
python -c 'import uuid; print uuid.uuid4()'
else
echo "Error: No UUID generation method available" >&2
return 1
fi
}
# Usage
UUID=$(get_uuid)
if [ $? -eq 0 ]; then
echo "Generated UUID: $UUID"
else
echo "Failed to generate UUID"
exit 1
fi