How to Create a Random Password on the Command Line

Sometimes you need to create a password or other random string of letters and numbers in a script or on the command line. I normally use the excellent tool pwgen, but sometimes that is not available on the system you are working on.

When pwgen isn’t available, you can sanitize the output of /dev/urandom so that you only get text and numbers. The following command will output a 10-character string:

cat /dev/urandom | tr -d -c [:alnum:] | head -c 10

Change the head -c 10 to make the output as long as you need it to be.