Skip to content

Instantly share code, notes, and snippets.

@elvis501
Created January 6, 2021 18:15
Show Gist options
  • Select an option

  • Save elvis501/4304400976193e26ade12cf5ba011df9 to your computer and use it in GitHub Desktop.

Select an option

Save elvis501/4304400976193e26ade12cf5ba011df9 to your computer and use it in GitHub Desktop.
ash PoorManRandomGenerator
#!/bin/sh
# Get a random number on Windows BusyBox alike, also works on most Unixes
PoorMansRandomGenerator() {
local digits="${1}" # The number of digits of the number to generate
local minimum=1
local maximum
local n=0
if [ "$digits" == "" ]; then
digits=5
fi
# Minimum already has a digit
for n in $(seq 1 $((digits-1))); do
minimum=$minimum"0"
maximum=$maximum"9"
done
maximum=$maximum"9"
# n=0; while [ $n -lt $minimum ]; do n=$n$(dd if=/dev/urandom bs=100 count=1 2>/dev/null | tr -cd '0-9'); done; n=$(echo $n | sed -e 's/^0//')
# bs=19 since if real random strikes, having a 19 digits number is not supported
while [ $n -lt $minimum ] || [ $n -gt $maximum ]; do
if [ $n -lt $minimum ]; then
# Add numbers
n=$n$(dd if=/dev/urandom bs=19 count=1 2>/dev/null | tr -cd '0-9')
n=$(echo $n | sed -e 's/^0//')
if [ "$n" == "" ]; then
n=0
fi
elif [ $n -gt $maximum ]; then
n=$(echo $n | sed 's/.$//')
fi
done
echo $n
}
echo $(PoorMansRandomGenerator 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment