CODE/2022-11-16

Seven Ways to Generate Random Values in Shell Scripts

Random values in shell scripts can be used for test data, identifiers, and tokens. Different sources have different guarantees: a value that looks random is not necessarily safe for security-sensitive use.

1. Bash's RANDOM variable

bash_snippet
Bash · 1 line|
printf '%s\n' "$RANDOM"
Bash generates an integer from 0 to 32767. This is convenient for demonstrations but is not cryptographically secure. Mapping it to a smaller range with modulo can introduce bias.

2. A timestamp

bash_snippet
Bash · 1 line|
date +%s
A timestamp is predictable and can repeat, so it is not a random number or a secret. The GNU date +%s%N form includes nanoseconds, but %N is not portable to the standard macOS date command and does not guarantee uniqueness.

3. Operating-system random bytes

bash_snippet
Bash · 2 lines|
od -An -N16 -tx1 /dev/urandom | tr -d ' \n'
printf '\n'
The example reads 16 bytes and displays them as hex. /dev/urandom is available on common Unix-like systems; behavior of /dev/random varies by operating system and version.

4. UUIDs

bash_snippet
Bash · 1 line|
uuidgen
UUIDs are useful as identifiers, but collisions remain possible and the implementation determines which UUID version is generated. Do not treat an arbitrary UUID as a password or secret.

5. OpenSSL

bash_snippet
Bash · 2 lines|
openssl rand -hex 16
openssl rand -base64 24
OpenSSL produces cryptographically secure random bytes. Hex output uses two characters per byte; Base64 can include punctuation and padding.

6. Choose from a custom character set

For a non-security-sensitive Bash demonstration:
bash_snippet
Bash · 2 lines|
characters=(a b c 0 1 2)
printf '%s\n' "${characters[RANDOM % ${#characters[@]}]}"
This uses Bash-specific array syntax and inherits $RANDOM's limitations. Use a cryptographically secure generator and an unbiased selection method for secrets.

7. Generate random integers with Python

When Python 3 is available, secrets provides unbiased selection for security-sensitive values:
bash_snippet
Bash · 1 line|
python3 -c 'import secrets; print(secrets.randbelow(100))'
This prints an integer from 0 through 99. A randomly selected port is not necessarily available; bind to port 0 in the application and let the operating system allocate an available port instead.

Security guidance

Do not derive passwords from timestamps, $RANDOM, checksums, or MD5 hashes of predictable values. For secrets, use a cryptographic random generator and choose an appropriate amount of entropy.
COMPANION ESSAYS / 思想脉络与互照篇目
同卷深读2026-05-22 ·

Installing Python 3 Alongside System Python on CentOS 7

同属「系统工程卷」脉络衍生思考与工程推演推演阅读 →
跨界互照2026-08-22 ·

我的书架:03|金融经管:经济运行、金融体系与企业治理

我的书架:03|金融经管:经济运行、金融体系与企业治理

跨领域对照思辨 · 从「思想随笔」视界互为印证推演阅读 →
RELATED INDEX / 相关阅读索引
柯航hang.ke·© 2014—2026
CC BY-NC 4.0·