- How to Generate Random String in Bash
- Generate Random String in Linux
- Conclusion
- Using «$RANDOM» to generate a random string in Bash
- 9 Answers 9
- How to Generate a Random String in Linux?
- Method 1: Using the Random Number Generator (RNG)
- Method 2: Using the OpenSSL Library
- Method 3: Using the UUID Generator
- Method 4: Using the mktemp Command
- Conclusion
- Generate Random String in Bash
- Use /dev/urandom Command
- Using openssl Command
- Further reading:
- Using uuid Command
- Conclusion
How to Generate Random String in Bash
A random string is a sequence of characters that is generated randomly, rather than being determined by a set pattern or predetermined sequence. Random strings are often used as passwords, keys, or identifiers, and they can be generated using a variety of methods.
Random strings can be generated using a computer program or a physical random number generator. The length and character set of a random string can be specified in the generation process. For example, a random string might be generated using only uppercase letters and digits, or it might include a combination of letters, digits, and special characters.
Generate Random String in Linux
To generate a random string in Bash, you can use the `openssl` command and the `base64` encoding function. Here is an example of how you can generate a random string of length 10:
This will generate a random string of length 10 using base64 encoding. The output will be a string of characters that includes letters, numbers, and special characters.
You can also use the `tr` command to remove any characters that you don’t want to include in your random string. For example, to generate a random string of length 10 that only includes uppercase letters and digits, you can use the following command:
openssl rand -base64 10 | tr -dc 'a-zA-Z0-9'
This will generate a random string of length 10 that only includes uppercase letters and digits.
You can adjust the length of the random string by changing the number passed to the `-base64` option. For example, to generate a random string of length 20, you can use the following command:
openssl rand -base64 20 | tr -dc 'a-zA-Z0-9'
This will generate a random string of length 20 that only includes uppercase letters and digits.
Conclusion
Random strings are useful because they are difficult to guess or predict, which makes them suitable for use as passwords or other forms of authentication. They can also be used to randomly assign identifiers to objects or records in a database, which can help to ensure that the identifiers are unique and not predictable.
This tutorial helped you to generate random strings in bash shell scripts and Linux command line interface.
Using «$RANDOM» to generate a random string in Bash
I am trying to use the Bash variable $RANDOM to create a random string that consists of 8 characters from a variable that contains integer and alphanumeric digits, e.g., var=»abcd1234ABCD» . How can I do that?
9 Answers 9
Use parameter expansion. $ is the number of possible characters, % is the modulo operator. $ selects the character(s) at position offset , i.e. 0 — length($chars) in our case.
chars=abcd1234ABCD for i in ; do echo -n "$:1>" done echo
@Dimareal: $RANDOM could be too large. By using modulo, the result can’t be greater than the length of the $chars, i.e. you can use it to index a random char.
Is there a version that works with «ash» and «sh» and not only with bash? I’m working on embedded system running OpenWrt and because or space restraints there is no space for bash. I get this error: # /tmp/rnd.sh /tmp/rnd.sh: line 5: syntax error: bad substitution
if chars contains escape characters, this can launch the bash command l . Try it with chars=’<=>| -,;:!/.»()[]<>*\&#%+012345689abcdefghiklmnopqrstuvwxyz’=>
For those looking for a random alpha-numeric string in bash:
The same as a well-documented function:
function rand-str < # Return random alpha-numeric string of given LENGTH # # Usage: VALUE=$(rand-str $LENGTH) # or: VALUE=$(rand-str) local DEFAULT_LENGTH=64 local LENGTH=$LC_ALL=C tr -dc A-Za-z0-9
Another way to generate a 32 bytes (for example) hexadecimal string:
add -u if you want uppercase characters instead.
OPTION 1 — Specific length, only lowercase letters, numbers and dashes
After generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs 😇 source
DEMO: x=100; while [ $x -gt 0 ]; do cat /proc/sys/kernel/random/uuid; x=$(($x-1)); done
be821d3c-c484-41d9-8fc8-eb8bc3683360 ba0b72e2-7969-481e-94c2-7a716c40c3e8 e0183127-a6e3-453b-87cd-7ea912afc49a 0ad84c92-186a-4c4d-aea9-5951083c9ed8 a42e0c6a-4f06-4c32-a289-dd0391f11aba a82b27d4-9bdb-403d-add4-8a72d36fb864 a16fcd29-02cd-448a-a048-ae6bde3c707c
OPTION 2 — No specific length, no openssl needed, only letters and numbers, slower than option 3
j0PYAlRI1r8zIoOSyBhh9MTtrhcI6d nrCaiO35BWWQvHE66PjMLGVJPkZ6GBK 0WUHqiXgxLq0V0mBw2d7uafhZt2s c1KyNeznHltcRrudYpLtDZIc1 edIUBRfttFHVM6Ru7h73StzDnG
OPTION 3 — No specific length, openssl needed, only letters and numbers, faster than option 2
openssl rand -base64 12 # only returns rand=$(openssl rand -base64 12) # only saves to var sed "s/[^a-zA-Z0-9]//g"
9FbVwZZRQeZSARCH 9f8869EVaUS2jA7Y V5TJ541atfSQQwNI V7tgXaVzmBhciXxS
Others options not necessarily related: uuidgen
How to Generate a Random String in Linux?
A random string is a sequence of characters that is generated using a random process or algorithm, without any specific pattern or structure. It ensures that the string is unique and not easily found by an attacker. It has various uses in Linux, such as generating passwords, creating unique identifiers or tokens, and testing software applications.
This guide will illustrate several methods to generate a random string in Linux:
- Method 1: Using the Random Number Generator (RNG)
- Method 2: Using the OpenSSL Library
- Method 3: Using the UUID Generator
- Method 4: Using the mktemp Command
Method 1: Using the Random Number Generator (RNG)
The “RNG” is a kernel-level device that generates random numbers by collecting entropy from various sources, such as hardware interrupts, mouse movement, and keyboard input. Use the “tr” command to translate these random numbers into a random string. Here’s an example:
The command “cat /dev/urandom | tr -dc ‘a-zA-Z0-9’ | fold -w 10 | head -n 1” is a one-line Linux command that generates a random alphanumeric string of 10 characters. The description of this command is mentioned below:
- cat /dev/urandom: reads random bytes from the Linux kernel’s random number generator device “/dev/urandom”.
- “tr -dc ‘a-zA-Z0-9’: deletes any characters that are not alphanumeric (letters or digits) in the input stream.
- “fold -w 10“: formats the output stream into lines of 10 characters each. This creates a string of 10 characters.
- “head -n 1“: selects only the first line of output from “fold -w 10”.
The script is written below:
$ cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1
This command generates a random string of 10 characters using the RNG.
Method 2: Using the OpenSSL Library
The OpenSSL library provides a random number generator that is used to generate random strings. The “openssl rand” command generates a sequence of random bytes.
An example with a brief description is provided below:
- “openssl rand”: command-line tool for generating random data using OpenSSL’s cryptographic functions.
- “-base64”: tells OpenSSL to encode the random data in base64 format (binary-to-text encoding scheme).
- “10”: specifies the number of random bytes to generate.
It generates a random sequence of bytes which is encoded in base64 format using the OpenSSL library.
Method 3: Using the UUID Generator
The UUID generator is a tool that generates universally unique identifiers (UUIDs). UUIDs are 128-bit values that can be used to generate random strings. Here’s an example:
An example is considered to generate the random string using the “UUID” generator. The description of the command is provided below:
- “tr -dc ‘a-zA-Z0-9’” command deletes characters that are not letters or digits in the input stream.
- “fold -w 10” formats the output stream into lines of 10 characters each. It creates a string of 10 characters.
- “head -n 1” command selects only the first line of output.
$ uuidgen | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1
This command generates a random string of 10 characters using the UUID generator.
Method 4: Using the mktemp Command
The “mktemp” command is utilized to create temporary files and directories. It can also be utilized to generate random strings. The description of the below command is given below:
- mktemp: command stands for “make temporary”.
- u: option tells it to only print the name of the file or directory that it creates, without actually creating it.
- XXXXXXXXXX: represents a sequence of ten X’s, which are replaced by mktemp with a random string of characters to create a unique filename.
An example is carried out to generate the random string. For instance, specify the “XXXXXXXXXX” to create a unique filename:
The output shows a random string of 10 characters via the mktemp command.
Conclusion
To generate a random string in Linux, use the “Random Number Generator”, “OpenSSL library”, “UUID generator”, and “mktemp” commands. The generated random string makes it difficult for an attacker to gain unauthorized access to a system or data.
This tutorial has demonstrated several methods to generate a random string in Linux.
Generate Random String in Bash
Bash provides a built-in variable $RANDOM that generates random numbers between 0 and 32767 . We can use this variable to generate random strings of any length. Here’s how to generate a random string of length 10 . The above code’s working is as follows:
- echo "$RANDOM" | md5sum generates a 32-character MD5 hash from the $RANDOM variable.
- printf '%s' converts the hash to a string.
- cut -c 1-10 selects the hash’s first 10 characters. And the echo command displays output on the console.
Use /dev/urandom Command
Use the /dev/urandom command to generate a random string in Bash.
The above code’s working is as follows:
- The tr -dc 'a-zA-Z0-9' command filters the output of /dev/urandom to include only alphanumeric characters, i.e., letters (both uppercase and lowercase) and digits.
- The fold -w 10 command wraps the output of tr after every 10 characters, creating a new line for each 10-character segment.
- Finally, the head -n 1 command selects the first line of the output, which contains the randomly generated string of 10 characters.
Using openssl Command
Use the openssl command to generate a random string in Bash.
The above code’s working is as follows:
- The openssl rand command generates random data.
- The -base64 encodes the generated data in Base64 format.
- And 15 specifies the number of bytes to generate, which translates 10 characters in Base64 format.
Further reading:
Check if String starts with another String in Bash
Get random number between 1 and 100 in Bash
Using uuid Command
Use uuid to generate a random string in Bash.
The above code’s working is as follows:
- The cat /proc/sys/kernel/random/uuid command generates a random UUID (Universally Unique Identifier) using the kernel’s random number generator and outputs it to the console.
- This part | sed 's/[-]//g' of the command pipes the previous command’s output to the sed command, which searches for any hyphens in the output and replaces them with nothing (i.e., removes them). The g flag means to do this globally (i.e., for all occurrences of hyphens in the output).
- This part | head -c 20 of the command pipes the output of the sed command to the head command, which takes the output’s first 20 characters and prints them to the console.
- And ; echo prints a newline character to the console after the random string
Conclusion
Considering the above solutions, we have explored four different methods to generate random strings in Bash. These methods include using the $Random , /dev/urandom , openssl , and uuid commands. You can choose the method that best suits your needs. Using these methods, you can generate random strings for various applications, such as password generation and token authentication.