The question is related to bash, Linux like Ubuntu, /dev/random and /dev/urandom .
How to generate a random number in a range which can be positive or negative, by /dev/random or /dev/urandom on bash ?
Known are:
- /dev/random and /dev/urandom generate more random numbers than random.
- Differents of /dev/random and /dev/urandom are: https://www.2uo.de/myths-about-urandom/
- https://heitorpb.github.io/bla/2020/04/07/bash-random-numbers/
Follow are a sample for a not searched solution to do it in a range on bash, by not searched function "RANDOM" and only in a positive range.
min=1
max=1000
rnd_count=$((RANDOM%(max-min+1)+min))
echo $rnd_count
Follow are a sample for a solution to do it by /dev/urandom on not searched language C:
> ##################################################
> # Random number generator, crypto quality
> #################################################
> # Returns a random floating point number between $min and $max, inclusive
> # With the default arguments, this is almost the same as expr rand()
> # Doesn't work on Windows, only on Unix-based OS such as MacOSX and Linux proc getRandomNumber {{min 0} {max 1}} { global tcl_platform
> if {$tcl_platform(platform) == "unix"} {
> set f [open /dev/urandom rb] ; set eightRandomBytes [read $f 8] ; close $f
> binary scan $eightRandomBytes h16 eightRandomBytesHex
> # n is an integer from 0 to 18446744073709551615 inclusive... lossless conversion
> set n [scan $eightRandomBytesHex %llx]
> # map n to min-max inclusive... maybe we lose a little randomness here (precision)
> set randomNumber [expr (($n/18446744073709551615.0) * ($max - $min)) + $min]
> return $randomNumber } else {
> error "getRandomNumber: Only works with Unix-based platforms" } }
Source: https://wiki.tcl-lang.org/page/Cryptographically+secure+random+numbers+using+%2Fdev%2Furandom
Follow are a sample for a partly solution by a not searches python solution by a python function:
python -c "import random; print random.randint(1,1000)"
A again, How to generate a random number in a range which can be positive or negative, by /dev/random or /dev/urandom on bash (not on other languages )?
A partly solution is to generate a random number by bash random or urandom on positive range works on follow way, how to do this on positive and negative range too, is unknown fo me. And its not pure bash. A pure bash solution are wanted.
echo "$(od -An -N4 -tu4 /dev/urandom) % 15 + 1" | b
c
or even better
echo "$(od -An -N4 -tu4 /dev/random) % 15 + 1" | bc
min=1; max=1000; rnd_count=$((RANDOM%($max-$min+1)+$min)); echo $rnd_count
and it gives a different number each time. Again, we are not here to teach you how to do it, but we are here to help in a Q&A style if you get stuck on something. – Terrance Feb 23 at 16:10