Estimated reading time: 2 minutes
In this article, we look at how to generate a random string in Linux. You can use these tools and commands to create secure and unique strings of random characters for passwords, tokens, keys, etc.
Table of contents
Generating a random string in Linux using the tr
command
Generating a random string in Linux using the tr
command is a straightforward method. We use the /dev/urandom
special file in Linux that provides random data. This is fed into the tr
command that translates or deletes unwanted characters from the standard input, making it simple and easy to use.
Example:
The below command generates a random string of 8 characters.
export LC_CTYPE=C; cat /dev/urandom | tr -dc 'a-zA-Z0-9!@#$%^&*()-_+=<>?' | head -c 8; echo
Note: The export LC_CTYPE=C;
command is necessary. The tr command expects valid text input, but /dev/urandom
produces binary data that can include invalid or non-printable characters.
Using the openssl
command
The openssl
command, the most common tool used for cryptography in Linux, can help generate random strings. This is especially useful for creating secure passwords or tokens. Here’s how you can use it to generate a random string:
export LC_CTYPE=C; openssl rand -base64 32 | tr -dc '[:alnum:]!#$%&()*+,-./:;<=>?@[]^_{|}~' | head -c 16; echo
The above command generates a random string of 16 characters.
Similarly, you can generate a Hexadecimal.
openssl rand -hex 16
This command generates a 16-byte random string encoded in hexadecimal.
Using the uuidgen
Command to Generate a Random String in Linux
The uuidgen
command can generate strings that can be used as unique keys or IDs.
Example:
uuidgen
This command generates a UUID (Universally Unique Identifier), which is a 36-character string formatted as 8-4-4-4-12
, consisting of hexadecimal digits and hyphens. Example output:
ED35820F-DE7A-4CF7-BDE7-BF4FAA10FBD0
UUIDs are unique and randomly generated, making them ideal for use as random strings in various applications. The uuidgen
command can generate session tokens, unique identifiers for database records, or any other scenario requiring a unique random string.