Bash $RANDOM Variable
Understanding and using the $RANDOM internal variable in Bash, including its open-source implementation
February 19, 2026
Bash $RANDOM Variable
In
When you need a simple random number, it can be used quickly without any external utilities.
bash, $RANDOM is a built-in variable that returns an integer between 0 and 32767 each time it's called.When you need a simple random number, it can be used quickly without any external utilities.
Basic Usage
The most basic usage is simply referencing the variable.
Generate random numbersh
To get a number within a specific range (e.g., 1-100), use the modulo operator (%).
Random number in range 1-100sh
Seeding RANDOM
Assigning a value to the
Providing the same seed will result in the same random sequence every time.
RANDOM variable sets an integer seed.Providing the same seed will result in the same random sequence every time.
Setting a seedsh
Deep Dive: Bash Open Source Code
Let's take a look at how
Looking at the Bash source code (
$RANDOM is implemented internally in Bash.Looking at the Bash source code (
variables.c), this variable is treated not as a simple variable, but as a dynamic variable.1. Dynamic Variable Registration
During the Bash initialization process, the
RANDOM variable is registered with special handlers via the initialize_dynamic_variables() function.variables.c - initialize_dynamic_variablesc
2. Generating Random Numbers
When a user calls
$RANDOM, it executes in the order get_random() -> get_random_number(), and the actual random number generation calls the brand() function (an internal LCG algorithm).variables.c - get_random_numberc
3. Seeding via Assignment
When a user assigns a value, such as
RANDOM=42, the assign_random function is called to initialize the random number generator's seed.variables.c - assign_randomc
Key Implementation Details
LCG (Linear Congruential Generator):Bash uses the lightweight brand() function for performance.
Its deterministic nature means the same seed will yield the same results.- Subshell Handling: To prevent subshells (like
$(echo $RANDOM)) from producing the same random sequence as their parent, the source code checksgetpid()and automatically performsseedrand()if the session differs. - att_integer:
$RANDOMis assigned an integer attribute at the time of creation, minimizing type conversion overhead during arithmetic operations. - The range of
$RANDOMis from 0 to 32767 (2^15 - 1). - It is not a cryptographically secure random number generator (CSPRNG), so it's not suitable for security-related purposes.
- If higher precision or security is required, it's recommended to use
/dev/urandom.