Is it possible to generate a random password from Bash? I'm looking for a simple command or script where I can choose the password length, ideally using a cryptographically secure source of randomness rather than Bash's built-in RANDOM variable.
3 Answers
A dedicated utility such as `pwgen` is another practical choice, especially if you want passwords that are easier to type or remember. Bash’s `$RANDOM` can make quick non-sensitive test values, but it shouldn’t be used for real passwords because its state and output are not strong enough for security.
If OpenSSL is available, this is a simple option: `openssl rand -base64 16`. It generates random bytes and encodes them as text. Adjust the number to change the amount of output, though Base64 may include characters that aren’t accepted by every password field.
For a password made from a specific character set, use `/dev/urandom`, which is intended for cryptographic randomness. For example: `LC_ALL=C tr -dc 'A-Za-z0-9!@#$%^&*()_+' < /dev/urandom | head -c 16; printf 'n'`. Change `16` to the desired length. Be aware that filtering can take a little longer when the character set is large.
Use `/dev/urandom` rather than `/dev/random` for this purpose. The former is designed to provide secure random data without unnecessarily waiting for extra entropy.

OpenSSL is convenient, but it isn’t part of Bash itself and may not be installed by default on every system.