Bash logo

Bash function to generate a secure random alphanumeric string

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

Home » GNU/Linux » Bash function to generate a secure random alphanumeric string

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

Take the following function and place it in your .bashrc file:

# 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
2fORqF7pau7bLafFuJbQNzK2D8yOLMnO

If needed you can add special characters to the tr command, for example (&_a-zA-Z0-9^*@ and ‘.

This will generate a more secure random string, like:

$ random-string
w4LD528^K52@rrYx@vfEg1wKwRSMQXoP
$ random-string
BnhUn_ScM&sIs(Yn0d40PxJKUQN0QkHg
$ random-string
cFg3FRPHB6SXcQ(f8wGr7y1RKSR1i^&i

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):

These random strings generated in Bash make ideal passwords. Rather use PowerShell? Check out “Create strong passwords in Windows“.

Jan Reilink
Jan Reilink

In my day to day work, I’m a systems administrator – DevOps / SRE and applications manager at Embrace – The Human Cloud. At Embrace we develop, maintain and host social intranets for our clients. Provide digital services and make working more efficient within various sectors.

Read why we can use your help and support ❤️

Articles: 173