Generating a random string on Linux & macOS

May 17, 2022 13:45 · 139 words · 1 minute read

Sometimes, you need to generate a random n-character long string. E.g. a password, some API token,…While you could use an external tool (e.g. the password generator of your password manager of choice, e.g. KeePassXC) or a website (e.g. random.org), you can also easily achieve this via your command line.

Here is a command that generates a 50-character random string, composed of upper and lower case letters & numbers. This command works both on Linux and macOS:

1
cat /dev/urandom | LC_ALL=C tr -dc 'a-zA-Z0-9' | fold -w 50 | head -n 1

You can modify the command to fit your needs:

  • fold -w <LENGTH_STRING>
  • head -n <NUMBER_OF_STRINGS>
  • tr -dc 'LIST_OF_CHARACTERS_TO_INCLUDE' (e.g. A-Za-z0-9!"#$%&'\''()*+,-./:;<=>?@[\]^_`{|}~ to include special characters that are frequently used in passwords)

To understand in detail what each command does, I recommend looking it up on explainshell.com.

(via unix.stackexchange.com)