HowTo: Linux Random Password Generator Command

How do I generate random passwords on the Linux command line using the bash shell? How to create random password using Linux command line options?

You can use the following shell function to generate random password. The function use the combination of the following commands and files:

  1. /dev/urandom file – Linux kernel’s random number generator source/interface. A read from the /dev/urandom device will not block waiting for more entropy.
  2. tr command – Translate or delete characters. Used to remove unwanted characters from /dev/urandom.
  3. head command – Output the first part of files.
  4. xargs command – build and execute command lines from standard input/pipe.

Bash function to create random password

Edit ~/.bashrc file, enter:
$ vi $HOME/.bashrc
Append the following code:

genpasswd() { 
	local l=$1
       	[ "$l" == "" ] && l=16
      	tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs 
}

Save and close the file. Source ~/.bashrc again, enter:
$ source ~/.bashrc

To generate random password, enter:
$ genpasswd
Sample outputs:

WGtkhETPJFZ2mtZk

To generate 8 character long random password, enter:
$ genpasswd 8
Sample outputs:

oj7Wqvb
Linux Random Password Generator Command

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.