All Linux systems have a special device “/dev/urandom” which can throw random bytes while reading. But this device gives binary data which may contain non-printable characters. However as we need human-readable characters for a password, we can pick all alpha-numeric characters out the random binary data read from the special device.

The following script reads a binary stream from /dev/urandom and picks up first 8 alpha-numeric characters and form a 8-chracter long random password. If you want to change the length of the password, change “-c8” option given to “head” to anything you want. For example “-c16” will give you 16-character long random password.

[neo@techpulp ~]# cat randpass.sh
#!/bin/bash

function randpass
{
echo `</dev/urandom tr -dc A-Za-z0-9 | head -c8`
}
randpass
[neo@techpulp ~]#

You can see the script generating different (random) password each when it is run.

[neo@techpulp ~]# sh randpass.sh
aS4S6A0d
[neo@techpulp ~]# sh randpass.sh
c9JqEMZP
[neo@techpulp ~]# sh randpass.sh
XktXtdhy
[neo@techpulp ~]#