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. It took me a while to even figure out that this change was what was causing the freeze and then even longer to tie it to the fact that my script was being fired off by PHP. I eventually came across this though:

http://stackoverflow.com/questions/20358686/running-bash-script-from-php-halts

Which told me that in effect, PHP doesn’t play nicely with /dev/urandom. Go figure… Thankfully, the person in the link up top recommended using this method:

var=$(openssl rand -base64 12 | tr -dc 'a-zA-Z0-9')

And that has worked well for me thus far. It seems to generate a random value every time so I will be sticking to this method going forward. I think I came across this method in the past but avoided it because it introduced openssl as an outside dependency. Considering the problems I had with the other two methods though I will just live with it.

1 of 1

This post has no comments. Be the first to leave one!

Join the discussion

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