I am working on a project where I need to generate a random value and assign it to a variable…

Initially I was doing this:

var=$(date +%s | sha512sum | base64 | head -c 12 ; echo)

Which was okay until I started executing my script more than once in a short period of time. Suddenly my random variable wasn’t so random and I was getting the same value multiple times in a row. This is a flaw of this method in that it is a hash of the value of the date (represented as an epoch value) at a given second.

UPDATE – 6/28/2016Someone pointed out to me that the OpenSSL method below also relies on the value of the date and time. I am not sure why it doesn’t experience the same issues as just using a sha512sum and, as I have a working method, am not going to investigate it further. I just wanted to clarify for the sake of accuracy. I am not an expert with this stuff.

So I had to can that method and that led me to trying this next:

var=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 12 | head -n 1)

This worked perfectly from the shell. Worked great when I executed a test script from the shell using it. However the PHP script that fired off the bash script would freeze whenever I used this. (more…)