How to Generate a Random String in Bash? [8 Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

A random string is a sequence of alphanumeric characters without following any specific pattern. To generate a random string in Bash, use the following syntaxes:

  1. Using mktempt: mktemp -u XXXXXXXXXX
  2. Using pwgen: pwgen [characters number] 1
  3. Using OpenSSL: openssl rand -base64 15
  4. Using base64: echo $RANDOM | base64 | head -c [characters number]; echo
  5. Using UUID: uuidgen | sed 's/[-]//g' | head -c 10; echo;

Random strings allow users to set unique identifiers and generate temporary filenames, passwords, and random keys. In this article, I will explore 8 different methods to generate random strings in Bash, including the above-mentioned 5 methods.

1. Using “mktemp” Command to Generate Random String

The mktemp command with the -u option displays a random filename without generating the file. You can specify the total number of characters in the filename by replacing X with the desired character count. Here is a command to generate a random string in bash:

mktemp -u XXXXXXXXXX
EXPLANATION

The mktemp command creates temporary files or directories. The -u option tells ‘mktemp’ to display the generated filename without creating the file. The XXXXXXXXXX specifies to generate the filename having 10 characters.

The mktemp command has generated a random string.Upon execution, the command generates a random number (2IRqvMuZ) containing 10 characters.

2. Using $RANDOM to Generate a Random String

Another way to generate random strings is by using the for loop and the $RANDOM command. In this example, a list of random characters, including lowercase, uppercase, and digits, is generated first. Then, these characters are assigned randomly as the elements of the array. Following is a complete Bash script demonstrating the process:

#!/bin/bash
a=()
for b in {a..z} {A..Z} {0..9};
   do
   a[$RANDOM]=$b
done
printf %s ${a[@]::6} $'\n'
EXPLANATION

First, the script part a=() initializes an empty array named ‘a’. Then, for b in {a..z} {A..Z} {0..9}; initiates a for loop that iterates over three ranges of characters: lowercase letters, uppercase letters, and digits. The variable b takes each character in these ranges. After that, a[$RANDOM]=$b inside the for loop assigns the value of b into a random element of array named a, where the array index is denoted by the output of the RANDOM command. Finally, printf %s ${a[@]::6} $'\n' prints the first 6 elements of the array a.

Random string is generated.The $RANDOM command has generated a random string 46cTzU.

3. Using md5 Hash to Generate Random String in Bash

Random strings can also be generated using the md5sum command along with the RANDOM command. In this process, the md5sum command will convert the integer value generated by the $RANDOM command to the MD5 hash value. Here is a complete Bash script for generating random strings using the md5 hash:

echo $RANDOM | md5sum | head -c 10; echo;
EXPLANATION

At first, the echo $RANDOM command generates a random integer and pipes it as input of the md5sum command that computes the MD5 hash value of that integer and passes it as input of the head command. The head command extracts only the first 10 characters of the input, and the echo command finally prints it.

The md5sum command has generated a random string.The generated random string is the MD5 hash value of a random integer.

4. Using UUID to Generate Random String in Bash

The uuidgen command generates a Universally Unique Identifier (UUID). Random strings can be picked from the output of the uuidgen command, excluding special characters such as hyphen (). Here is a complete command to do so:

uuidgen | sed 's/[-]//g' | head -c 10; echo;
EXPLANATION

The UUID is piped to the sed 's/[-]//g' command that removes all the hyphens from the UUID. After that, this is passed to the head -c 10; echo; command that extracts the first 10 characters of the UUID it receives and prints it on the terminal.

The uuidgen command has generated a random string.The image shows that the uuidgen command has generated a random string.

5. Using Pseudo Devices to Generate Random String in Bash

The files inside the /dev directory serve as the bridge between the kernel and the hardware. For this reason, these files are called pseudo devices. One of these files is the /dev/urandom file that allows users to access random numbers generated by the kernel. Then, convert them to alphanumeric values to generate random strings. Here is the Bash command to do so:

cat /dev/urandom | tr -dc '[:alpha:]' | fold -w ${1:-10} | head -n 1
EXPLANATION

The command part cat /dev/urandom reads random bytes from the /dev/urandom file containing random data the operating system provides. Then, these bytes are passed to the tr -dc '[:alpha:]' command, where the tr (translate) command filters out non-alphabetic characters and keeps only the letters. After that, the output of the tr common is passed to the fold -w ${1:-10} command that wraps the input lines to a maximum width of 10 characters. These lines are finally piped to the head -n 1 command that prints the first line of the output on the terminal.

Random string has been generated.See from the image that pseudo devices generated a random string.

Note: This approach is not cryptographically secure for sensitive applications.

6. Using Base64 to Generate Random String in Bash

Converting the output of the $RANDOM command into the base64 command is another approach to generating random strings. The base64 command encodes the input data into ASCII characters. Execute the command below to generate random strings using the base64 command:

echo $RANDOM | base64 | head -c 10; echo
EXPLANATION

Here, echo $RANDOM generates a random integer between 0 and 32767 and passes it to the base64 command. It encodes the input data into ASCII characters. After that, the ASCII characters are passed to the head -c 10; echo command that extracts the first 10 characters and prints them on the terminal.

The base64 has generated a random string.See from the image the $RANDOM command with the base64 command has generated a random string.

7. Using OpenSSL Pseudo to Generate Random Bytes

The rand subcommand of the OpenSSL toolkit generates random data, which can be encoded into ASCII characters utilizing the -base64 option. Follow the command to do so:

openssl rand -base64 15
EXPLANATION

The openssl is a toolkit, and rand is a subcommand of OpenSSL. The rand generates random data. Here, the -base64 option encodes those generated binary data into ASCII characters. Here, ‘15’ after the command specifies the number of bytes of random data to generate.

The openssl rand command has generated a random string.After execution, the OpenSSL command generated a random string.

8. Using “pwgen” Command to Generate Random string in Bash

The pwgen (password generator) command can generate a password with a specified number of characters. These are random strings. For this, execute the below command:

pwgen 5 1
EXPLANATION

Here, the pwgen (password generator) will generate one random password with 5 characters combining letters of uppercase, lowercase, and numbers.

The pwgen command created a random string.The pwgen command has generated a random string Pol6n having 5 characters.

If the pwgen command is not found, install it by executing:

Debian: apt-get install pwgen

Ubuntu: apt-get install pwgen

Alpine: apk add pwgen

Arch Linux: pacman -S pwgen

Kali Linux: apt-get install pwgen

Fedora: dnf install pwgen

OS X: brew install pwgen

Raspbian: apt-get install pwgen

Docker: docker run cmd.cat/pwgen pwgen

Conclusion

In conclusion, random strings can be generated in various ways. Mastering this skill will enable programmers to assign unique identifiers, set passwords, and enhance data manipulation. Reading this article will make individuals skillful in effectively generating random strings in Bash.

People Also Ask

How does random work in Bash?

The echo $RANDOM command in bash generates a random integer between 0 and 32767. Users can use this integer to print it on the terminal or assign it to a unique identifier.

Is regex only for string?

Yes, the regex (regular expression) is only for strings. This string can be filenames or input streams also. The regex provides pattern-matching operators, allowing users to check if a string matches a specified pattern.

How do I generate random text in Linux?

To generate random text in Linux, access the /dev/urandom file. It possesses system-generated random data. Then, the non-alphabetic characters should be removed to generate random text in Linux. Follow the syntax below to generate random text in Linux:

cat /dev/urandom | tr -dc '[:alpha:]' | fold -w ${1:-10} | head -n 1

How do I find a string in bash?

To find a string in bash, use the grep command. It is a pattern-searching tool in bash that allows users to search within a string for a substring.

Related Articles


<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial

Rate this post
Susmit Das Gupta

Hello everyone. I am Susmit Das Gupta, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Mechanical Engineering graduate from Bangladesh University of Engineering and Technology. Besides my routine works, I find interest in going through new things, exploring new places, and capturing landscapes. Read Full Bio

Leave a Comment