DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Parambir Singh
Parambir Singh

Posted on

TIL - Unix shells have a $RANDOM env variable

Ever wanted to add some randomness to your shell script? No I don't mean to make them flaky!

Unix shells provide a $RANDOM environment variable that we can use in our shell commands or scripts:

% echo $RANDOM 
21290
% echo $RANDOM
8367

The seed for the random number generator can be changed as follows:

% RANDOM=12345
% echo $RANDOM
5758

Generating random numbers in a range

We can use awk for generating random integers in a given range. For example, to generate a random number between 1 and 10 (inclusive):

% awk -v seed=$RANDOM 'BEGIN{srand(seed); print int(rand()*10+1)}'
10
% awk -v seed=$RANDOM 'BEGIN{srand(seed); print int(rand()*10+1)}'
4
% awk -v seed=$RANDOM 'BEGIN{srand(seed); print int(rand()*10+1)}'
1

More details at:

Top comments (2)

Collapse
 
nektro profile image
Meghan (she/her)

Note: this value is generated on the fly and not available in all evironments

Collapse
 
parambirs profile image
Parambir Singh

Yes, you are right. I'm using fish shell these days and it doesn't have this feature.

Image description

Join the One Year Club

You can earn this badge by being a registered member of the DEV Community for at least one year. Create an account and get started today.