Last active
October 23, 2015 19:17
-
-
Save yitsushi/8287916e311d36cf8663 to your computer and use it in GitHub Desktop.
Random password generator in bash (and zsh)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# shell logger (if DEBUG = 1) | |
log() { | |
if [[ "$DEBUG" = 1 ]] | |
then | |
echo " *** [`date +'%x %T'`] $*" >&2 | |
fi | |
} | |
# Random password generator | |
# 1st parameter is the length of the password (15 by default) | |
randomPassword() { | |
# Darwin hack to sed and tr in binary data | |
OLD_LC_CTYPE=$LC_CTYPE | |
if [[ "`uname`" = "Darwin" ]] | |
then | |
LC_CTYPE=C | |
fi | |
# End hack | |
length=15 | |
if [[ -n $1 ]]; then length=$1; fi | |
baseLength=$(( $length * 10 )) | |
randomBytes=`dd if=/dev/urandom bs=$baseLength count=1 2> /dev/null | tr '\n' ' '` | |
# $ sign before the sed string means: hey shell, I want to translate that before | |
password=$(sed -Ee $'s/[^\x21-\x7E]//g' <<< $randomBytes | cut -c 1-$length) | |
if [[ ${#password} -lt $length ]] | |
then | |
password="${password}`randomPassword $(( $length - ${#password} ))`" | |
fi | |
log "Current length is ${#password}" | |
LC_CTYPE=$OLD_LC_CTYPE # revert to original LC_CTYPE | |
echo $password | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment