Simple console password generator script

Here is where you can post tips and tricks to share with other users of MX. Do not ask for help in this Forum.
Message
Author
MCreaves
Posts: 40
Joined: Sun May 19, 2019 10:52 pm

Simple console password generator script

#1 Post by MCreaves »

Just a simple bash script to generate passwords.

Code: Select all

#!/bin/bash
#
# Use this script to generate a random password in console/bash
#
# Example:
# ./genpass.sh 25 a
# Will generate a 25 character random password using only letters


if [ -z "$1" ]
  then
    echo "Please supply a password length"
    echo "i.e. 20 for 20 character password"
    echo "-----------"
    echo "./genpass.sh 20 a"
    echo "would be 20 char pass using letters and numbers"
    echo "-----------"
    echo "./genpass.sh 20 b"
    echo "would be 20 char pass using letters and numbers"
    echo "and special characters"
    exit 1
fi

if [ -z "$2" ]
  then
    echo "Please specify whether to use letters"
    echo "and numbers only, or letters with numbers"
    echo "and special characters"
    echo "------------"
    echo "./genpass.sh 20 a"
    echo "would be 20 char pass using letters and numbers"
    echo "------------"
    echo "./genpass.sh 20 b"
    echo "would be 20 char pass using letters and numbers"
    echo "and special characters"
    exit 1
fi

if [ $2 = "a" ]
then 
  # Letters and numbers only
  tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w "$1" | head -n 1
elif [ $2 = "b" ]
then
  # Letters, numbers, special characters
  tr -dc 'a-zA-Z0-9~!@#$%^&*_()+}{?></";.,[]=-' < /dev/urandom | fold -w "$1" | head -n 1
else
  echo "Wrong argument, second arg can only be a or b"
  exit 1
fi

Return to “Tips & Tricks by users”