The question is related on Linux like Debian or Ubuntu, bash and a given function which use RANDOM.
Every improvement should use bash only.
Given are the follow function:
getRND(){
min="${1:-1}" ## min is the first parameter, or 1 if no parameter is given
max="${2:-100}" ## max is the second parameter, or 100 if no parameter is given
rnd_count=$((RANDOM%(max-min+1)+min));
echo "$rnd_count"
}
var=$(getRND -10 10) # Call the function
echo $var # output
How too:
- Improve the randomness
The solution is sought for Linux systems on which no bash 5.1 is installed already and therefore no SRANDOM can be used up to now.
3
Answers
And this is how it looks when the code from the question and the code from KamilCuk's answer are combined in one function for doing the random more equally distributed:
Remark: Its looks like it can be used in a range bigger than +-32000
making seed for RANDOM in main shell and expecting it to be favoured in subshell is pointless because new shell makes its own initialization of seed.
so you need to seed and use RANDOM of main shell and pass value into another function for transformation.
here is an example how to make your seed to work:
Sooo write your own SRANDOM with your own semantics. Ex:
and then:
If you are not happy with the way shell arithmetic expansion works, then… use a different tool.
bc
calculator has unlimited range.You can write your own C program with
getrandom()
and compile it on the flyecho "int main() { stuff(); }" | gcc -xc - && ./a.out; rm ./a.out
basically granting you any semantics you want. There are also other scripting languages, like perl, python, ruby, all most probably with their own big-number libraries and urandom number generation implementations. Sky the limit.Is from my perspective a pointless limitation – overall, I am paid for results, not really "how" I solve problems. Anyway, you could, giving you a bunch of ideas how to proceed:
/dev/urandom
and convert the bytes into a number.read
exit status, cause the byte may be zero byte or newline.bc
is commonly available.