Bash function to generate a random alphanumeric string

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

# Generate a random string of 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
}Code language: Bash (bash)

An example usage and output is

$ random-string
2fORqF7pau7bLafFuJbQNzK2D8yOLMnOCode language: Bash (bash)

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

tr -dc '(\&\_a-zA-Z0-9\^\*\@'Code language: Bash (bash)

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

$ random-string
$ random-string
$ random-string
cFg3FRPHB6SXcQ(f8wGr7y1RKSR1i^&iCode language: Bash (bash)

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/nullCode language: Bash (bash)

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

would be nice if everyone would stop catting all over themselves as the < filename parameter does the same thing.

Here’s an example that works on all POSIX systems even Sun unix and AIX and is always going to get 32 characters (ie a DWORD byte read 8 times):

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

These random strings generated in Bash make ideal passwords. Or do you prefer to generate pseudo-random strings with OpenSSL for this task?

Jan Reilink

Hi, my name is Jan. I am not a hacker, coder, developer or guru. I am merely an application manager / systems administrator, doing my daily thing at Embrace - The Human Cloud. In the past I worked for clidn and Vevida. With over 20 years of experience, my specialties include Windows Server, IIS, Linux (CentOS, Debian), security, PHP, websites & optimization. I blog at

1 Comment
Oldest Most Voted
Inline Feedbacks
View all comments