DEV Community

Parambir Singh
Parambir Singh

Posted on

4

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:

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more