In this tutorial, we shall look at various ways we can generate random strings in bash. This functionality can be useful when creating usernames, passwords, or seed data.
Method 1: md5 Hash
The very first method we can use to generate a random string in bash is md5 checksums. Bash has the $RANDOM variable, which produces a random number. We can pipe this value to md5sum to get a random string.
The $RANDOM variable is always random. As a result, the md5 checksum produces is always random.
Method 2: UUID
You can also use the kernel UUID generator in /proc/sys/kernel/random/uuid. This will give you will get a unique hexadecimal value that you can convert to a random string using the sed and head command:
Method 3: Pseudo devices
You have heard the phrase, “Everything in Linux is a file.” One of the concepts that make this statement true is the ability to express devices as files.
Files located in /dev are known as pseudo devices; they act as bridges between the kernel and the hardware. One of the files in this directory is the uradom file.
The urandom file provides an interface to access the kernel random number generator. Hence, we can use it to generate a random string as illustrated below:
We pipe the output of urandom to tr, which generates alphanumeric values and then folds the values to the width of up to 20 characters. Finally, we get one lined string with head -n.
To get multiple values at once, change the value of head -n to the number of lines required.
Method 4: Base64
You can also use the base64 utility to generate a random string. For example, using the $RANDOM variable, we can do:
Method 5: OpenSSL Pseudo Random Bytes
OpenSSL rand command allows you to generate random bytes based on the type specified. These types include base63 and hex values.
Or use base64 as:
In closing, bash provides various utilities you can use to generate random strings. Therefore, all you need to do is combine various tools and develop a clever way to get random strings that suit your needs.