Shell Random Number Generator
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
http://www.krazyworks.com/?p=1 http://www.krazyworks.com/?p=2 http://www.krazyworks.com/?p=3 ... http://www.krazyworks.com/?p=1000
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
http://www.krazyworks.com/?p=343 http://www.krazyworks.com/?p=790 http://www.krazyworks.com/?p=910 http://www.krazyworks.com/?p=327 http://www.krazyworks.com/?p=639 http://www.krazyworks.com/?p=959 http://www.krazyworks.com/?p=971 http://www.krazyworks.com/?p=75 http://www.krazyworks.com/?p=283 http://www.krazyworks.com/?p=496
Popularity: 34% [?]




