Last active
March 27, 2023 19:06
-
-
Save pmarreck/e65f457e8755e461a87db7c94d479248 to your computer and use it in GitHub Desktop.
Deterministic random number generator in Bash
This file contains 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
# deterministic random number generator | |
# Usage: [DRANDOM_SEED=<whatever>] drandom [-h|--hex|--help] | |
# Outputs an integer between 0 and 2^256-1 or an equivalent hex string if -h|--hex is specified | |
drandom() { | |
needs sha256sum || return 1 | |
# if unset, initialize to hash of nanoseconds since epoch, | |
# otherwise, set to hash of previous seed | |
if [ -z $DRANDOM_SEED ]; then | |
export DRANDOM_SEED="$(date +%s%N | sha256sum | cut -d' ' -f1)" | |
else | |
export DRANDOM_SEED="$(echo -n $DRANDOM_SEED | sha256sum | cut -d' ' -f1)" | |
fi | |
case "$1" in | |
--hex) | |
echo $DRANDOM_SEED | |
;; | |
-h|--help) | |
echo "drandom is a deterministic random number generator." | |
echo "Usage: [DRANDOM_SEED=<whatever>] drandom [--hex]" | |
echo "Outputs an integer between 0 and 2^256-1 or an equivalent hex string if --hex is specified" | |
echo "If no seed is specified, it will be seeded to the sha256 hash of the nanoseconds since epoch on first run." | |
;; | |
*) | |
# convert to unsigned int from 256-bit hex | |
printf "%u\n" $((16#$DRANDOM_SEED)) | |
;; | |
esac | |
} | |
# well, this should be easy to test... | |
assert "$(DRANDOM_SEED=0 drandom)" == "10852665827039288777" | |
assert "$(DRANDOM_SEED=1 drandom --hex)" == "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment