-
-
Save markusfisch/6110640 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash | |
# Generate a pseudo UUID | |
uuid() | |
{ | |
local N B C='89ab' | |
for (( N=0; N < 16; ++N )) | |
do | |
B=$(( $RANDOM%256 )) | |
case $N in | |
6) | |
printf '4%x' $(( B%16 )) | |
;; | |
8) | |
printf '%c%x' ${C:$RANDOM%${#C}:1} $(( B%16 )) | |
;; | |
3 | 5 | 7 | 9) | |
printf '%02x-' $B | |
;; | |
*) | |
printf '%02x' $B | |
;; | |
esac | |
done | |
echo | |
} | |
if [ "$BASH_SOURCE" == "$0" ] | |
then | |
uuid | |
fi |
Here is the whole thing restructured using only a case
block (no ifs):
uuid()
{
local N B C='89ab'
for (( N=0; N < 16; ++N ))
do
B=$(( $RANDOM%256 ))
case $N in
6)
printf '4%x' $(( B%16 ))
;;
8)
printf '%c%x' ${C:$RANDOM%${#C}:1} $(( B%16 ))
;;
3 | 5 | 7 | 9)
printf '%02x-' $B
;;
*)
printf '%02x' $B
;;
esac
done
echo
}
Note that substring expansion introduces an arithmetic context so it's not necessary to use $(()) inside it. I moved the assignment of C
outside the loop. Also, the values for the modulus operations are incorrect (15 should be 16 and 255 should be 256).
Sorry for the late reaction; didn't see your comment until now.
You're right! Updated the gist to your implementation. Thanks a lot!
if you need a crypto secure version using urandom:
https://github.com/lowerpower/UUID-with-bash
Hello. fyi, this can be much much simpler. RANDOM gives 16 bits of randomness, looping over %256 is wasting so much potential. Just:
HAS_SRANDOM=$(( (BASH_VERSINFO[0] << 16 | BASH_VERSINFO[1] << 8 | BASH_VERSINFO[2]) >= 0x050100 ))
if ((HAS_SRANDOM)); then
printf -v L_v "%08x%08x%08x%08x" \
"$SRANDOM" "$(( SRANDOM & 0x3FFFFFFF | 0x40000000 ))" "$SRANDOM" "$SRANDOM"
else
printf -v L_v "%04x%04x%04x%04x""%04x%04x%04x%04x" \
"$RANDOM" "$RANDOM" "$(( RANDOM & 0x3FFF | 0x4000 ))" "$RANDOM" \
"$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM"
fi
L_v=${L_v::8}-${L_v:8:4}-4${L_v:13:3}-${L_v:16:4}-${L_v:20}
echo "$L_v"
Hello. fyi, this can be much much simpler. RANDOM gives 16 bits of randomness, looping over %256 is wasting so much potential. Just:
Sorry, but RANDOM
is only 15 bits.
The
T
variable can be eliminated and thefor T
loop can be changed to: