Onjsdev

Share


How to Generate Random Strings in Bash


By onjsdev

Nov 30th, 2023

When working with Bash scripting, generating random strings can be a useful task for various purposes, such as creating unique identifiers, temporary filenames, or passwords. In this article, we'll explore different methods to generate random strings in Bash.

Method 1: Using /dev/urandom

Bash provides access to the /dev/urandom device, which generates pseudo-random data. You can use this as a source to create random strings. Here's a simple one-liner:

echo $(cat /dev/urandom | LC_ALL=C tr -dc 'a-zA-Z0-9' | head -c 12)

This command uses tr to delete characters that are not alphanumeric and limits the length to 12 characters with head -c 12.

Method 2: Utilizing the $RANDOM Variable

Bash has a built-in variable called $RANDOM that returns a random integer between 0 and 32767. You can use this variable to generate random strings:

echo $(cat /dev/urandom | LC_ALL=C tr -dc 'a-zA-Z0-9' | head -c $((RANDOM % 12 + 1)))

In this example, the length of the string is limited to a random value between 1 and 12.

Method 3: Shuffling Characters

You can also use the shuf command to shuffle characters and create random strings:

echo $(echo {a..z} {A..Z} {0..9} | tr -d ' ' | fold -w 1 | shuf | tr -d '\n' | head -c 12)

Here's a breakdown

  • fold -w 1 ensures that each character is on a separate line.
  • shuf shuffles the lines.
  • tr -d '\n' removes the newline characters.
  • head -c 12 limits the output to 12 characters.

Conclusion

Generating random strings in Bash can be achieved through various methods, depending on your requirements and the tools available on your system. Whether you prefer using /dev/urandom, the $RANDOM variable, or shuf, these techniques offer flexibility for creating random strings for different purposes in your Bash scripts.

Thank you for reading.