Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number between range in shell

How I can generate random number between 0-60 in sh (/bin/sh, not bash)? This is a satellite box, there is no $RANDOM variable, and other goods [cksum, od (od -vAn -N4 -tu4 < /dev/urandom)].

I want to randomize a crontab job's time.

like image 560
Adrian Avatar asked Jan 12 '11 20:01

Adrian


People also ask

How do you generate a random number from 1 to 10 in Bash?

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.

What is $random in Bash?

$RANDOM is an internal Bash function (not a constant) that returns a pseudorandom integer in the range 0 - 32767. $RANDOM should not be used to generate an encryption key. Example 9-23. Generating random numbers. #!/bin/bash # $RANDOM returns a different random integer at each invocation. #

What is $$ in shell script?

$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing.


2 Answers

If you have tr, head and /dev/urandom, you can write this:

tr -cd 0-9 </dev/urandom | head -c 3

Then you have to use the remainder operator to put in 0-60 range.

like image 120
marco Avatar answered Oct 27 '22 03:10

marco


How about using the nanoseconds of system time?

date +%N

It isn't like you need cryptographically useful numbers here.

Depending on which version of /bin/sh it is, you may be able to do:

$(( date +%N % 60 ))

If it doesn't support the $(()) syntax, but you have dc, you could try:

dc -e `date +%N`' 60 % p'

Without knowing which operating system, version of /bin/sh or what tools are available it is hard to come up with a solution guaranteed to work.

like image 34
Thedward Avatar answered Oct 27 '22 04:10

Thedward