Sleeping for a random amount of time in a shell script

You can use the special $RANDOM environment variable to get a random number and divide it by the maximum number of seconds that you want to wait. Use the remainder as the number of seconds to sleep since it will always be between zero and the max you specified. This example will sleep anywhere between zero and 10 minutes (600 seconds)

 /bin/sleep/sleep   `/usr/bin/expr $RANDOM % 600`

Purists will note that it isn’t truly random. The maximum value for $RANDOM is 32767 which is not evenly divisible by most likely values, but it is close enough.

Leave a Reply

Your email address will not be published.