LiveFire Labs - Online UNIX Training - Company Logo


Online UNIX Training with Hands-on Internet Lab


"Eliminate the expense and inconvenience of classroom training without eliminating the classroom experience."

 


Home
Internet Lab
Console Access
Sample Course

Student Login


LiveFire Labs' UNIX Tip, Trick, or Shell Script of the Week - View


Questions? Call
1.888.843.1637 or send us email

October 20, 2003 - Useful Shell Scripting Variables - Part IV - RANDOM

RANDOM is a peculiar shell variable, but useful nonetheless.  Peculiar because its value changes each time it is referenced (yes, this is by design).

As you may have already guessed, RANDOM is a random number generator.  The number generated is an integer between 0 and 32767, and can come in handy when writing shell scripts.  To determine if a shell you're using supports this variable, the following command can be used:

$ print $RANDOM $RANDOM
29302 8082
$

Two different numbers will be displayed if it’s supported, otherwise you will see nothing.

Assigning a numeric value to RANDOM prior to referencing it will initialize (seed) the sequence of random numbers:

$ RANDOM=10
$ print $RANDOM
4543
$ print $RANDOM
28214
$ print $RANDOM
11245
$

This same sequence of numbers can be repeated by initializing RANDOM using the same seed:

$ RANDOM=10
$ print $RANDOM
4543
$ print $RANDOM
28214
$ print $RANDOM
11245
$

Just to get you thinking about potential uses for this handy variable, consider the following...

When writing a shell script to automate the process of adding new user accounts, it may be desirable to generate a unique initial password for each account.  Using the value provided by RANDOM for all or part of the password would accomplish this.  It would be wise to use the PID of the process creating the account(s) to seed the generator:

<previous code>

RANDOM=$$
x=$RANDOM

<subsequent code>


Learn more...
  

If you are new to the UNIX or Linux operating system and would like to learn more, you may want to consider registering for LiveFire Labs' UNIX and Linux Operating System Fundamentals online training course.

If you already have a solid grasp of the fundamentals but would like to learn more about the Korn shell and basic and advanced shell scripting, taking our Korn Shell Scripting course will be beneficial to you.

Our innovative hands-on training model allows you to learn UNIX by completing hands-on exercises on real servers in our Internet Lab.


More Tips...

· 
Popular UNIX Tips from the Past

spacer Box Border
 

Receive the UNIX Tip, Trick, or Shell Script of the Week by Email


First Name:


Email Address:






   1.888.843.1637

Home - Contact us - Company info - Privacy Statement   

 
©2002-2003 LiveFire Labs.  All rights reserved.
Linux® is a registered trademark of Linus Torvalds, author and developer of this public domain operating system.
UNIX® is a registered trademark of The Open Group in the United States and other countries.