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 |
✦ 卷终 · 柯航存卷 ✦