CODE/2022-11-16

Generating Random Strings in Shell Scripts

Shell scripts sometimes need random identifiers or tokens. The right method depends on whether the value is merely a temporary identifier or must be difficult to guess.

Generate a secure token with OpenSSL

bash_snippet
Bash · 1 line|
openssl rand -hex 16
This generates 16 random bytes represented as 32 hexadecimal characters. For a Base64-encoded value, use:
bash_snippet
Bash · 1 line|
openssl rand -base64 24
Base64 output can contain /, +, and =; account for that if the result must be URL-safe.

Use the operating system random source

On systems that provide /dev/urandom, od can render a fixed number of bytes as hexadecimal:
bash_snippet
Bash · 2 lines|
od -An -N16 -tx1 /dev/urandom | tr -d ' \n'
printf '\n'

Generate a UUID

bash_snippet
Bash · 1 line|
uuidgen
A UUID is convenient for identifiers but is not a substitute for a secret token. The exact UUID version and availability of uuidgen depend on the platform.

Understand the limitations of shell randomness

Bash's $RANDOM is useful for simple non-security-sensitive examples, but it is not a cryptographically secure source. Timestamps are predictable, and hashing a timestamp or $RANDOM with MD5 does not make the result secure. Use a cryptographic random generator for passwords, session tokens, or other secrets.
For a batch of independent tokens, call the secure generator once per item:
bash_snippet
Bash · 3 lines|
for i in {1..5}; do
openssl rand -hex 16
done
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·