Networking

Unix and Linux network configuration. Multiple network interfaces. Bridged NICs. High-availability network configurations.

Applications

Reviews of latest Unix and Linux software. Helpful tips for application support admins. Automating application support.

Data

Disk partitioning, filesystems, directories, and files. Volume management, logical volumes, HA filesystems. Backups and disaster recovery.

Monitoring

Distributed server monitoring. Server performance and capacity planning. Monitoring applications, network status and user activity.

Commands & Shells

Cool Unix shell commands and options. Command-line tools and application. Things every Unix sysadmin needs to know.

Home » Commands & Shells, Scripts

Shell Random Number Generator

Submitted by on August 4, 2009 – 2:58 pm 8 Comments

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
   https://www.krazyworks.com/?p=1
   
About
https://www.krazyworks.com/?p=3 ... https://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
   https://www.krazyworks.com/?p=343
   https://www.krazyworks.com/?p=790
   https://www.krazyworks.com/?p=910
   https://www.krazyworks.com/?p=327
   https://www.krazyworks.com/?p=639
   https://www.krazyworks.com/?p=959
   https://www.krazyworks.com/?p=971
   https://www.krazyworks.com/?p=75
   https://www.krazyworks.com/?p=283
   https://www.krazyworks.com/?p=496
Print Friendly, PDF & Email

8 Comments »

  • Dr Hank says:

    Does anyone do it or know someone that does it? What stakes do they play and how many hours a week do they play?

  • JDOGG1122 says:

    Instructions: Do all of the following questions. Please comment all lines as to show me what is happening. Also make sure each script runs until the user decides to exit. Use your BASH Shell. In addition to submitting a written copy of the code via the dropbox you MUST also create a folder in your UNIX account named, project. In that folder should be all of the scripts you wrote for the final project, named final1, final2, etc. You must also give me read and execute permissions. If you do not submit your code and allow me to access your scripts you will not receive credit for the final project. Programs written in other programming languages will not be accepted. Finally, all scripts MUST loop until the user is done using it.

    1. Create a program that will ask the user if they want to add, subtract, multiply or divide two user inputted numbers. Then give the response as follows:

    The sum of number1 and number 2 is: Answer

    The difference of number1 and number2 is: Answer

    The product of number1 and number2 is: Answer

    The quotient of Number1 and Number2 is: Answer

    Please note: ONLY IF the user enters 0 as the second number, let the user know that if they choose divide that a division by zero error will occur.

    2. Create a program that will allow a user to type in a number, while the program outputs that number in words. Example, if you typed in 21, the computer would respond with twenty-one. Please allow the program to work for 0-30. If a number typed in is not in that range, be sure to let the user know.

    3. Write an If Statement that will allow the user to type in a month, then the program will respond with the holiday in that month. (You only need to list 1 holiday per month.) If there is no holiday, then have the computer respond there is no holiday in this month. Also let the user know if they typed a month that does not exist.

    4. Write a program that will allow a user to input as many numbers as the user wants (use “q” as the choice that ends the user input). The program will then respond:

    Highest Number: Answer

    Lowest Number: Answer

    Sum of the numbers: Answer

    Average of the numbers: Answer

    5. Create a Number guessing game. Have the computer pick a number from 0-60 using the Random Number Generator I provided.

    Then allow the user to guess at the number until the user gets it right. Please include the following:

    a) Keep a counter of how many guesses were made, and then tell the user how many guesses it took.

    b) As the user guesses, tell the user whether the guess is too high or too low.

    6. Write a program that will allow a user to type in a number, then the number will either count up to the number provided by the user or count down from that number. In addition, create a menu that will let the user choose which counter they wish to use. In both cases that counter will either count down to 0, or start counting from 0.

  • sean says:

    I want to go about building some software that can do this:

    Enable user to type in a website prefix (eg. http://www.example123.com/random/forum.php?id=)
    Set up a number generator (so it could be random, or in order, from any value to any value, eg. 1 to 200)

    Then the programme would work with your browser of choice- searching each website you’ve generated, eg. http://www.example123.com/random/forum.php?id=1, http://www.example123.com/random/forum.php?id= 2, http://www.example123.com/random/forum.php?id=3

    (All automatically)

    Then present you at the end, (once it had completed all the searches) with a log of screenshots taken of the web addresses searched.

    How on earth could I go about creating something like this? Is it even possible?
    I hope I’ve explained it clearly. As you can see, I have very limited knowledge of computer programming.

    Thanks!

  • SteveO says:

    I started learning VBscript just to learn another type of code, and I was wondering what is the point of implementing VBscript since it only seems to work in IE? It seems that javascript would eliminate any need for VBscript.

  • Milk84 says:

    Okay, I’m obviously not very adept at programming. I understand that the following code will wipe a hard drive with zeros, but I’m not understanding the first FOR command and also the if=/dev/random. I would be very cool if someone could break down the code below and help me to understand what’s what with it if possible.

    Complete code:

    for (( i = 0;i<11;i++ )); do
    dd if=/dev/random of=/dev/hda && dd if=/dev/zero of=/dev/hda
    done

    2nd part of question:

    If I wanted to create a batch file to do this to run in say Knoppix, how would I go about doing so?

    Thanks a million for educating me.

  • Gamer959 says:

    What is the best casino online play with? Lasvegas or Nobel casino or maybe some else?

  • zigg3ns says:

    An .exe file which can run 100,000 iterations per second when executed through command prompt runs only 50 iterations per second when made to run from another program using the system function. What may be the reason for this and more importantly how to speed it up? What I don’t know is whether the function transfers control to the OS so that I could try to speed up the OS by may be increasing the RAM that the OS can use or whether it operates by itself in which case I could decrease the RAM that the OS can use so that more of it is available to my process. I have tried making it High Priority which increased the speed by about 20%, but my project requires that the speed increase to at least 200%. Further, the project specifically requires calling the process using system from another program. This is one requirement for which I don’t think there is any way to bypass.

    The project I am working on is hoped to culminate in an Open Source Random Number Generator for which I am spending a lot of my time, money and effort. I request people out there to help me with this problem so that my desire of donating my time, money and effort for the betterment of the people is fulfilled.

    Please help.
    Thank you very much in anticipation.
    IIT Kharagpur
    I am looping myself so that I can get data from the process that the function runs, one at a time. The looping is happening using a for loop. When I loop the called process writing a code within itself without calling it from another program, it loops 100,000 times per second as mentioned above but it doesn’t do the same when looped from outside using the system () function.

    I will be happy to post the program, but since this is a collaborative project, I will first have to ask my colleagues. That may take a few days. But I think the information I have given should be pretty sufficient. Anyway, Sorry! Please understand.

    The system that I am working on is Windows 7 (Ultimate), 1.5 GB RAM, Pentium Dual Core Processor (1.46 GHz and1.47 GHz).

    Dear J, Are you sure that for loop is slower than a while loop? (I have been taught that for loop works faster than a while loop for doing exactly the same work that the for loop does.)
    Dear Fred W Sir,

    Thank you so much for your highly detailed and prompt reply.

    system() has a great property that it returns the value returned by the called process. execl() works fantastically fast but sadly doesn’t return the value returned by the called process which is a requirement since I use the value returned to generate a random number. popen and pclose do work but they also work at the same speed as system().

    The 2nd option that you suggested gives an error on my system, from which, what I understand is that the system function doesn’t understand the full Path (even though, surprisingly, exactly the same command works when inputted directly in command prompt).

    Dear sir, I am novice for the remaining 3 options. Could you tell me among the remaining 3 options, which one is most promising and the source to learn them.

    I am saving the values returned by the called process, which is same as those returned by system(), in a file (using C code).

  • simply complicated says:

    Ok . So I am taking this challenge where you choose your pokemon based ona random number generator. The pokemon I have to train are Torterra, Giraferig, Hipowdon, Tentacruel, Roserade and Machoke. I need some help with moves for each pokemon and any other info you can give. I don’t EV train or look at their natures, so none of that is needed.
    Anybody who wants to try these challenges go to http://www.hupitgaming.com/forum/33-pokemon/637456-pokemon-challenges

Leave a Reply

%d bloggers like this: