Bash function to generate a random alphanumeric string

You can use this Bash function in your .bashrc file to generate a random alphanumeric string. This comes in handy when you need to generate a long, secure password for example. Adjust to your needs.

# Generate a random 32 character alphanumeric string (upper 
# and lowercase) and numbers in Bash
random-string() {
        cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w ${1:-32} | head -n 1

An example usage and output is

$ random-string

If needed you can add special characters to the tr command:

tr -dc '(\&\_a-zA-Z0-9\^\*\@'

This’ll generate a more secure random string, like:

$ random-string
$ random-string
$ random-string

An example that works on all POSIX systems even Oracle Solaris and IBM AIX. It provides 32 random characters (ie a DWORD byte, or 32 bits), read 8 times):

tr -dc '[:alnum:]' < /dev/urandom | dd bs=4 count=8 2>/dev/null

This is kindly taken from ghost’s comment in earthgecko’s gist And denzuko writes:


Leave a Reply

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