Set Bash Variables Random Numbers?
The calculator for this page is switched off while it is checked. The formula is below, and the worked example in the article shows how to use it by hand.
Yes, you can set Bash variables to random numbers using the built-in $RANDOM variable, which returns a pseudo-random integer between 0 and 32767 each time it is referenced. You can assign it directly, scale it to a desired range, or use it to generate random strings for scripting and testing.
Formula
The formula used in the calculator is:
random_value = min + (RANDOM % (max - min + 1))
Where:
RANDOMis the Bash built-in variable that expands to a random integer between 0 and 32767 (inclusive).minandmaxare the lower and upper bounds of the desired range (integers).%is the modulo operator that gives the remainder of the division ofRANDOMby the range size.
This yields an integer in the inclusive range [min, max]. Note that the modulo method has a slight bias because 32768 is not always divisible by the range size, but for most scripting purposes it is acceptable.
Worked Example
Using the calculator defaults: min = 0, max = 100, and assuming Bash returns RANDOM=12345:
- Calculate the range size:
max - min + 1 = 100 - 0 + 1 = 101. - Compute the modulo:
12345 % 101 = 12345 - (122 * 101) = 12345 - 12322 = 23. - Add the minimum:
0 + 23 = 23.
The result is 23. The calculator will show a different number each time you run it, but the formula remains the same.
How Bash Generates Random Numbers
Bash’s $RANDOM is a special shell variable that generates a pseudo-random integer using a linear congruential generator (LCG). The seed is initialized from the system’s entropy pool (e.g., /dev/urandom) at shell startup, so each new shell session produces a different sequence. The value is in the range 0 to 32767 (2^15 – 1) because it is based on a 15-bit integer.
To assign a random number to a variable, you simply write:
myvar=$RANDOM
Every time you reference $RANDOM, it generates a new number. This is important: if you need the same random value multiple times, you must assign it once and then use the variable.
Scaling to a Specific Range
Often you need a random number within a specific range, not the full 0-32767. The standard approach is to use the modulo operator:
# Random number between 1 and 10
rand=$(( (RANDOM % 10) + 1 ))
Explanation: RANDOM % 10 gives a value from 0 to 9, then adding 1 shifts it to 1-10. For a range from 0 to N-1, just use RANDOM % N.
If you need a range with a negative minimum, you can adjust the formula:
# Random number between -5 and 5
rand=$(( (RANDOM % 11) - 5 ))
Because RANDOM % 11 gives 0-10, subtracting 5 gives -5 to 5.
Generating Random Strings
For random strings (e.g., passwords, filenames), you can combine $RANDOM with other tools. A common method uses /dev/urandom and tr:
# Random 8-character alphanumeric string
rand_str=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 8)
Alternatively, you can use $RANDOM to pick from a set of characters:
chars='abcdefghijklmnopqrstuvwxyz0123456789'
rand_str=''
for i in {1..8}; do
rand_str+="${chars:RANDOM%${#chars}:1}"
done
This loops 8 times, each time selecting a character based on a random index.
Common Pitfalls and Misconceptions
One common mistake is assuming $RANDOM produces a uniform distribution across all ranges. Because 32768 is not divisible by every integer, the modulo method introduces a small bias for ranges that don’t divide 32768 evenly. For example, a range of 0-2 (size 3) will have 0 appearing slightly more often than 1 or 2. For most scripts this is negligible, but for cryptographic or statistical work you should use /dev/urandom or a dedicated tool like shuf.
Another misconception is that $RANDOM is unpredictable. It is pseudo-random, meaning it is deterministic given the seed. An attacker who can observe some outputs might be able to predict future ones. For security-sensitive tasks, never use $RANDOM; use openssl rand or /dev/urandom directly.
Also, note that $RANDOM is a Bash-specific feature. In POSIX sh (e.g., dash), it is not available. If you need portability, consider using awk or external commands.
Alternatives to $RANDOM
Bash offers several other ways to get randomness, each with different strengths:
shuf: Generates random permutations or picks random lines. For a random number in a range, useshuf -i 1-10 -n1./dev/urandom: Provides high-quality random bytes. Read it withodorheadto get numbers.$RANDOMwithSECONDSor$$(PID) as a seed: Not recommended, as it reduces randomness.openssl rand: Cryptographically secure random numbers, useful for security.awk 'BEGIN{srand(); print rand()}': Uses a different pseudo-random generator, but still not cryptographic.
For most shell scripting, $RANDOM is sufficient and fast. For security, use /dev/urandom or openssl.
Frequently Asked Questions
How do I get a random number between 1 and 100 in Bash?
Use echo $(( (RANDOM % 100) + 1 )). The modulo gives 0-99, adding 1 gives 1-100. Remember to include the parentheses to ensure correct order of operations.
Why does $RANDOM always give the same number in a loop?
It shouldn’t. Each reference to $RANDOM generates a new number. If you see the same number, you might be assigning it once and reusing the variable. For example, r=$RANDOM; echo $r; echo $r prints the same value twice because $r holds the value, not the generator.
Can I seed $RANDOM to get reproducible results?
Bash does not provide a direct way to seed $RANDOM. However, you can achieve reproducibility by using a fixed seed with other tools, like awk 'BEGIN{srand(42); print rand()}'. For $RANDOM, you could set RANDOM=42 as an assignment, but this is not officially documented and may not work consistently across Bash versions.
Is $RANDOM cryptographically secure?
No. $RANDOM is a pseudo-random generator, not cryptographically secure. For passwords, tokens, or any security-sensitive data, use openssl rand or read from /dev/urandom.
How do I generate a random floating-point number?
Bash only does integer arithmetic. Use awk or bc. For example, awk 'BEGIN{srand(); print rand()}' gives a float between 0 and 1. To get a float in a range, multiply and add: awk -v min=1 -v max=10 'BEGIN{srand(); print min+rand()*(max-min)}'.
Does $RANDOM work in all shells?
No, it is a Bash extension. In POSIX sh (dash), it is not available. For portability, use awk or external commands like shuf or od.
Related
Formula used
in n | Number of values | - | 5 | 1 in min | Minimum value | - | 0 | 0 in max | Maximum value | - | 100 | 1 out rnd | Random value | - | min + (RANDOM % (max - min + 1)) | 0
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.