Get random numbers under BASH and DOS

Both Linux Bash and Windows DOS support random number generation. The random number is ‘stored’ in a system environment variable named “RANDOM” (I believe this variable links to a script to generate the actual random numbers on both systems), use it in the same way as you use other ENV variables.  E.g.

On Linux:

1
echo $RANDOM

;

On Windows:

1
echo %RANDOM%

;

Share this:
Facebook Linkedin Twitter Digg Email

2 Comments

  1. random says:

    What about use %RANDOM% inside FOR in ms-DOS
    ex:
    FOR /L %%a IN (0,1,100) DO @echo %RANDOM%
    I would generate 100 DIFFERENT random numbers but the line above generates 100 times the same number!!! What’s up?

  2. 9rivers says:

    Aha! random, you are in trouble with the so-called “delayed variable expansion” in DOS batch. This has been discussed here: http://blogs.msdn.com/b/oldnewthing/archive/2006/08/23/714650.aspx .

    In your case, in order to get 100 DIFFERENT random numbers, you have to enable the delayed variable expansion for your DOS console. Do this “cmd /v” to start it, or add this “setlocal enabledelayexpansion” in your batch file. Then, another important thing is to change the “%” symbol to “!” for the variables you want them to be expanded on the fly. E.g. try
    “FOR /L %%a IN (0,1,100) DO @echo !RANDOM!” in your file, you’ll get 100 DIFFERENT random numbers!

Leave a Reply