Generate Random Number in UNIX Shell Script

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 $
Code language: Arduino (arduino)
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 $
Code language: Arduino (arduino)
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 $
Code language: Arduino (arduino)
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>
Code language: Arduino (arduino)
Share
Published by
Viral Patel
Tags: Functions Shell Script random number shell Unix Shell Script

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

5 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

5 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

5 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

5 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago