Monday, 25 August 2014

Generating random strings with tr and urandom in Bash

I recently needed a script to generate a random string in a bash script for naming multiple PCs in a desktop deployment of about 200 Linux PCs. I wanted each PC to have a unique name, this is a job for a bash script.

A google search turned up this site immediately and is where I got what i needed to get started.

From this site, I liked a combination of tr, urandom and head to generate the strings because it turns out that you can use tr to generate a whole load of different strings, alphanumeric strings, and even hexadecimal numbers!

So down to business, I wanted an letters only, 6 characters long, easy

  tr -dc "[:alpha:]" < /dev/urandom | head -c 6

If you put this into a bash prompt, you do not get a new line at the end so an echo at the end will fix that.

  tr -dc "[:alpha:]" < /dev/urandom | head -c 6;echo

This looks like what I want and now that I had played around with this on the command line, it's now ready to go into a bash script:


  STRING=`tr -dc "[:alpha:]" < /dev/urandom | head -c 6`
  echo $STRING

Note the ` back-ticks around what we were testing so that we can assign it to the STRING variable. The echo at the end is no longer needed too. Here's the script running.

  waltersa@p1155-awdeb:~$ ./ 

Getting a random hex number would be easy too, simply change [:alpha:] to [:xdigit:] Here's a list of some of the possibilities, from the tr man page.... have fun.

              all letters and digits

              all letters

              all digits

              all lower case letters

              all printable characters, including space

              all punctuation characters

              all upper case letters

              all hexadecimal digits