In a recent project, I needed a function that would generate a random string for me. In my case, I was creating a random file name to store some data, but there are other uses as well, so I am posting the BASH code here in the hope that it will help others out ther eon the net writing BASH scripts and need a good random string function:
#!/bin/bash function randomString { # if a param was passed, it's the length of the string we want if [[ -n $1 ]] && [[ "$1" -lt 20 ]]; then local myStrLength=$1; else # otherwise set to default local myStrLength=8; fi local mySeedNumber=$$`date +%N`; # seed will be the pid + nanoseconds local myRandomString=$( echo $mySeedNumber | md5sum | md5sum ); # create our actual random string myRandomResult="${myRandomString:2:myStrLength}" } randomString 10; echo $myRandomResult;