Created
April 21, 2025 19:33
-
-
Save geoffjay/bc79518d2e5e8337a7933211e988409d to your computer and use it in GitHub Desktop.
Generate ULID in bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# taken from https://www.usefulids.com/resources/generate-ulid-in-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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment