Generate ULIDs in Bash

Resources  |  Generate ULIDs in Bash

Generating a ULID (Universally Unique Lexicographically Sortable Identifier) directly in Bash can be done using external tools such as uuidgen and base32. Since there isn't a built-in ULID generator in Bash, we can achieve this using a combination of commands and some script logic.

Generate ULID in Bash

To generate a ULID, we need to create a timestamp and a random part. Here's how you can do it in Bash:

  1. Install Required Tools:

    • Ensure you have openssl (for generating random bytes) and base32 (for encoding) installed.
  2. Bash Script: Create a Bash script that combines the current timestamp with random data, and then formats it as a ULID.

#!/bin/bash

# Function to convert timestamp to ULID-compatible format
timestamp_to_ulid() {
  local timestamp=$1
  # ULID timestamp is milliseconds since UNIX epoch
  printf '%010X' $((timestamp * 1000))
}

# Function to generate random part of ULID
random_part() {
  # Generate 16 random bytes and encode them in base32 (remove padding)
  openssl rand -out /dev/stdout -hex 10 | xxd -r -p | base32 | tr -d '=' | head -c 16
}

# Get current timestamp in milliseconds
current_timestamp=$(date +%s)

# Convert timestamp to ULID-compatible format
timestamp_ulid=$(timestamp_to_ulid $current_timestamp)

# Generate random part of ULID
random_ulid=$(random_part)

# Combine timestamp and random part to form ULID
ulid="${timestamp_ulid}${random_ulid}"

echo $ulid

Explanation

  1. Timestamp Conversion:

    • timestamp_to_ulid function converts the current timestamp in seconds to milliseconds and formats it as a hexadecimal string.
  2. Random Part Generation:

    • random_part function uses openssl rand to generate 16 random bytes and base32 to encode them in base32 without padding.
  3. Combining Parts:

    • The script combines the timestamp and random parts to form a full ULID.

Running the Script

  1. Save the Script: Save the above script as generate_ulid.sh.

  2. Make the Script Executable:

    chmod +x generate_ulid.sh
    
  3. Run the Script:

    ./generate_ulid.sh
    

This script will output a ULID similar to 01ARZ3NDEKTSV4RRFFQ69G5FAV. Note that this method approximates the ULID specification but may not be as robust as a dedicated library in other programming languages. For critical applications, consider using a more reliable method in a programming language with proper ULID library support.