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
Enter fullscreen mode Exit fullscreen mode

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

% RANDOM=12345
% echo $RANDOM
5758
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.