Shell Random Number Generator

Shell Random Number Generator

By:


Sometimes, in the course of writing shell script, a need arises for some random input. Using the built-in $RANDOM shell variable will give you a random number from 0 to 32767 . Let's take a look at a few examples making use of this shell variable in a number of handy ways. These examples are presented using "while" loops to better illustrate the variable's functionality. The basic usage is as follows:

echo $RANDOM

What if you need a random number no greater than 10? No problem:

echo "'expr $RANDOM % 11'"

How about a random number from 1 to 10 (no zeros)? Here you go:

echo "'expr $RANDOM % 10'+1"|bc -l

Same thing for a random number from 1 to 1000:

echo "'expr $RANDOM % 1000'+1"|bc -l

Now, what if you need a random from 1 to 100,000? As you know, the $RANDOM variable only goes to 32767, but there is a simple workaround: just stack two of them side by side (and, no, we will not be diving into a discussion of how random is "random" in this case):

echo "'expr ${RANDOM}${RANDOM} % 100000'+1"|bc -l

So what useful tasks can you perform using the random number generator? You can randomize various lists. For example, you have a long list of URLs and you want to download random ten links. Let's say our list of URLs is /tmp/url_list.txt:

cat /tmp/url_list.txt

link1
link2
link3
...
link100

Now we randomize the list and grab ten random URLs:

cat /tmp/url_list.txt | while read url
do
urls_total=$(wc -l /tmp/url_list.txt | awk '{print $1}')
random_number=$(echo "'expr $RANDOM % $urls_total'+1"|bc -l)
echo "${random_number}^$url"
done | sort -n | sed 's/[0-9]*^//' | head -10

link13
link72
link23
link12
link87
link2
link76
link17
link87
link51


About the Author:
http://www.krazyworks.com



Article Originally Published On: http://www.articlesnatch.com


|

Loading...
Related....
Videos...

Recent Computers-and-Technology Articles

Comments

Still can't find what you are looking for? Search for it!

Loading

Copyright 2005-2011 ArticleSnatch, LLC - All Rights Reserved.
Privacy Policy | Terms of Service.