How would I generate an inclusive random number between 1 to 10 in Bash Shell Script?
Would it be $(RANDOM 1+10)?
$(( ( RANDOM % 10 ) + 1 ))
EDIT. Changed brackets into parenthesis according to the comment. http://web.archive.org/web/20150206070451/http://islandlinux.org/howto/generate-random-numbers-bash-scripting
% 10 reduces the result to a set of ranges from 0-9. However, the very top set only has a range of 0-7. Thus, there are two fewer draws for 8 & 9 than 0-7. The + 1 translates this to a bias against 9 & 10. This would be a major flaw in security contexts - an RNG must not display bias, and at scale this is noticeable. Further explanation: Anatomy of a pseudorandom number generator - visualising Cryptocat's buggy PRNG.man bash, "Each time this parameter is referenced, a random integer between 0 and 32767 is generated." Note that this is not a bash error, it's an error of the implementer. Assuming bash implemented $RANDOM correctly, there should be a fair draw from numbers 0 to 32767, but because you can't divide that evenly into groups of 10, there is a very small bias against 9 and 10 in this implementation. Most people shouldn't need to worry about this, because you shouldn't be using $RANDOM for security purposes anyway.Simplest solution would be to use tool which allows you to directly specify ranges, like gnu shuf
shuf -i1-10 -n1
If you want to use $RANDOM, it would be more precise to throw out the last 8 numbers in 0...32767, and just treat it as 0...32759, since taking 0...32767 mod 10 you get the following distribution
0-8 each: 3277
8-9 each: 3276
So, slightly slower but more precise would be
while :; do ran=$RANDOM; ((ran < 32760)) && echo $(((ran%10)+1)) && break; done
/bin/sh even though the question requests bash. The shuf technique appears to work in both bash and sh.To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970.
echo $RANDOM % 10 + 1 | bc
date +%s to get a big number. echo $(date +%s) % 4 | bcecho just prints the string (variable substitution happens before the command is processed, so $RANDOM is already replaced with an integer by that point), bc is what actually evaluates it when the | redirects the stdout from the echo into the stdin of the bcYou can also use /dev/urandom:
grep -m1 -ao '[0-9]' /dev/urandom | sed s/0/10/ | head -n1
sed s/0/10/ !Here is example of pseudo-random generator when neither $RANDOM nor /dev/urandom is available
echo $(date +%S) | grep -o .$ | sed s/0/10/
export CUDA_VISIBLE_DEVICES=$((( RANDOM % 8 )))