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 there on the net writing BASH scripts and need a good random string function:

function randomString {
        # if a param was passed, it's the length of the string we want
        if [[ -n $1 ]]; then
                local myStrLength=$1;
                # otherwise set to default
                local myStrLength=16;

        # create character set, update this as needed

        for i in `seq 1 $myStrLength`; do
              char=${charSet:$RANDOM % ${#charSet}:1}

randomString $1;
echo $myRandomString;

Save this to a script file (I called mine using the command-line ‘nano’ editor:

me@home:~ $ nano

Now mark it as an executable script:

me@home:~ $ chmod +x

And now you should be able to run it and pass it whatever you want as the length of your string:

me@home:~ $ ./
me@home:~ $ ./ 32
me@home:~ $ ./ 64
me@home:~ $ ./ 256

Hope this helps someone!

Leave a Reply

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

five + twelve =