Bash Random Password Generator

Submitted by jbreland on Thu, 05/06/2010 - 17:50

Random password generators are certainly nothing new, but they, of course, come in handy from time to time. Here's a quick and easy Bash function to do the job:

# Generate a random password
#  $1 = number of characters; defaults to 32
#  $2 = include special characters; 1 = yes, 0 = no; defaults to 1
function randpass() {
  [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
    cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
    echo
}

I use this a good bit myself; it can be as strong (or weak) as you need, and only uses core Linux/UNIX commands, so it should work anywhere. Here are a few examples to demonstrate the flags:

$ randpass
UEJ1#QgdFbiJDvCiG*WbQoM:yM'y*[5d
$ randpass 10
4y8jsp#}&(
$ randpass 20 0
RT3Q3SJEgvnQDgz616RJ