Generate a random number
Pick a random integer in a range — useful for sampling, sleep jitter, or simulation seeds.
How to generate a random number in each shell
Bashunix
shuf -i 1-100 -n 1Zshunix
shuf -i 1-100 -n 1Fishunix
shuf -i 1-100 -n 1PowerShellwindows
Get-Random -Minimum 1 -Maximum 101`-Maximum` is **exclusive** (off-by-one trap when porting from Linux `shuf -i 1-100` which is INCLUSIVE on both ends). `Get-Random` is NOT cryptographic on pwsh 5.1; use `[Security.Cryptography.RandomNumberGenerator]::GetInt32(1, 101)` on 6+ for crypto-quality.
cmd.exewindows
powershell -NoProfile -Command "Get-Random -Minimum 1 -Maximum 101"cmd has `%RANDOM%` (0–32767), but it suffers the same 15-bit PRNG limits as bash `$RANDOM`. Shell out to PowerShell for both larger ranges and crypto-quality.
Equivalents listed for Bash, Zsh, Fish, PowerShell, cmd.exe.
Gotchas & notes
- GNU `shuf -i MIN-MAX -n 1` works on Linux but is NOT in BSD/macOS coreutils. macOS portable: `jot -r 1 MIN MAX` (`-r` random, 1 number, range inclusive on both ends). Cross-platform script: detect via `command -v shuf || command -v jot`. `brew install coreutils` provides `gshuf` on macOS — but `jot` ships natively and matches macOS conventions.
- bash `$((RANDOM % 100 + 1))` has MODULO BIAS — if `RANDOM` max (32767) isn't a multiple of 100, the lower 67 numbers (32767 mod 100 = 67) appear slightly more often. The bias is small for tiny ranges but unacceptable for sampling/simulation. Use `shuf -i 1-100 -n 1` or `awk 'BEGIN{srand(); print int(rand()*100)+1}'` (still not crypto, but no modulo bias).
- PowerShell `Get-Random` range convention is HALF-OPEN: `-Minimum 1 -Maximum 100` returns 1..99, NOT 1..100. The exclusive-upper-bound matches .NET `Random.Next(int min, int maxExclusive)` and Python `random.randrange`. Bash `shuf` and `jot -r` are CLOSED-CLOSED. When porting between shells, always read the range docs — off-by-one bugs in random selection are invisible until they bite (e.g., a list-index out-of-range that reproduces only ~1% of the time).
- For a non-uniform distribution (e.g. weighted): build a cumulative-probability array and binary-search a uniform random. For sleep jitter in retry loops use `sleep $((RANDOM % 5 + 1))` (bash) or `Start-Sleep -Seconds (Get-Random -Min 1 -Max 6)` (pwsh) — non-crypto is fine here because guessability doesn't matter, only spread.
Related tasks
- Generate a random password— Produce a strong random password from the command line — cryptographic-quality, not `$RANDOM`.
- Generate a random string— Produce a fixed-length random ASCII string — useful for tokens, slugs, file suffixes, and test fixtures.
- Shuffle lines in a file— Randomize the order of lines in a file — useful for sampling, A/B-bucketing, and test fixtures.
- Pick a random line from a file— Select one random line from a file — useful for fortune-style picks, A/B bucketing, and test sampling.