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.

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:

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

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

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

This is kindly taken from ghost’s comment in earthgecko’s gist bash.generate.random.alphanumeric.string.sh.

Bash function to generate a random alphanumeric string Click To Tweet
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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