Skip to content

Instantly share code, notes, and snippets.

@jcttrll
Last active May 2, 2025 16:52
Show Gist options
  • Save jcttrll/d3f01cafc8a2974923835c59e9057f25 to your computer and use it in GitHub Desktop.
Save jcttrll/d3f01cafc8a2974923835c59e9057f25 to your computer and use it in GitHub Desktop.
Generate version 4 UUID using only /dev/urandom and Bash built-ins
#!/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