In this tutorial, we shall appear at several means we can deliver random strings in bash. This features can be handy when producing usernames, passwords, or seed info.
System 1: md5 Hash
The pretty very first approach we can use to create a random string in bash is md5 checksums. Bash has the $RANDOM variable, which provides a random amount. We can pipe this value to md5sum to get a random string.
echo $RANDOM | md5sum | head -c 20 echo
The $RANDOM variable is always random. As a consequence, the md5 checksum produces is normally random.
Technique 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 transform to a random string using the sed and head command:
For case in point:
cat /proc/sys/kernel/random/uuid | sed ‘s/[-]//g’ | head -c 20 echo
Strategy 3: Pseudo units
You have listened to the phrase, “Everything in Linux is a file.” Just one of the concepts that make this assertion correct is the means to express units as files.
Documents situated in /dev are recognised 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 offers an interface to accessibility the kernel random number generator. As a result, we can use it to make a random string as illustrated below:
cat /dev/urandom | tr -dc ‘[:alpha:]’ | fold -w $1:-20 | head -n 1
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. Eventually, we get a single lined string with head -n.
To get several values at the moment, alter the worth of head -n to the range of strains essential.
cat /dev/urandom | tr -dc ‘[:alpha:]’ | fold -w $1:-20 | head -n 5
Process 4: Base64
You can also use the base64 utility to make a random string. For illustration, applying the $RANDOM variable, we can do:
echo $RANDOM | foundation64 | head -c 20 echo
Method 5: OpenSSL Pseudo Random Bytes
OpenSSL rand command lets you to deliver random bytes based on the kind specified. These varieties involve base63 and hex values.
For case in point:
openssl rand -hex 20
Or use base64 as:
openssl rand -base64 21
In closing, bash offers numerous utilities you can use to make random strings. Consequently, all you need to have to do is merge different tools and produce a intelligent way to get random strings that fit your demands.