BASH – Generate a Random String

BASH – Generate a Random String

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 myRandomString="";
        # generate random characters until our random string is longer than the requested size
        while [ ${#myRandomString} -lt ${myStrLength} ]; do
                myRandomString=${myRandomString}`head -c 8192 /dev/urandom | tr -dc '[:alnum:]' | tail -c 20 `;
        done
        
        # trim to exact requested length
        myRandomResult="${myRandomString:2:myStrLength}"
}

randomString $1;
echo $myRandomResult;

Leave a Reply

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

1 × four =