Generate Random String in Bash

Generate random String in Bash

Using $RANDOM Variable

Use the $RANDOM variable with cut command to 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.

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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *