Last active
May 2, 2025 16:52
-
-
Save jcttrll/d3f01cafc8a2974923835c59e9057f25 to your computer and use it in GitHub Desktop.
Generate version 4 UUID using only /dev/urandom and Bash built-ins
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
#!/usr/bin/env bash | |
uuidV4() { | |
local LC_ALL=C IFS= | |
local byte i | |
local -a bytes | |
for ((i = 0; i < 16; i++)); do | |
read -r -d '' -n1 byte && printf -v byte '%d' "'$byte" | |
bytes[i]=$byte | |
done </dev/urandom | |
bytes[6]=$(( (bytes[6] & 0xf) | 0x40 )) | |
bytes[8]=$(( (bytes[8] & 0x3f) | 0x80 )) | |
printf '%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n' "${bytes[@]}" | |
} | |
uuidV4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment