FUNDAMENTALS A Complete Guide for Beginners
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:
- Using mktempt:
mktemp -u XXXXXXXXXX
- Using pwgen:
pwgen [characters number] 1
- Using OpenSSL:
openssl rand -base64 15
- Using base64:
echo $RANDOM | base64 | head -c [characters number]; echo
- 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
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.
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'
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.
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;
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.
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;
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.
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
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.
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
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.
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
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.
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
Here, the pwgen
(password generator) will generate one random password with 5 characters combining letters of uppercase, lowercase, and numbers.
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
- How to Convert a Bash String to Int? [8 Methods]
- How to Format a String in Bash? [Methods, Examples]
- How to Convert Bash String to Uppercase? [7 Methods]
- How to Convert Bash String to Lowercase? [7 Methods]
- How to Replace String in Bash? [5 Methods]
- How to Trim String in Bash? [6 Methods]
- How to Truncate String in Bash? [5 Methods]
- How to Remove Character from String in Bash? [7+ Methods]
- How to Remove First Character From Bash String? [7 Methods]
- How to Remove Last Character from Bash String [6 Methods]
- How to Use String Functions in Bash? [Examples Included]
- How to Manipulate Bash String Array [5 Ways]
- How to Use “Here String” in Bash? [Basic to Advance]
- Encode and Decode with “base64” in Bash [6 Examples]
- How to Use “eval” Command in Bash? [8 Practical Examples]
- How to Get the First Character from Bash String? [8 Methods]
<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial