I believe in binary Zen. You're either at one with everything, or at zero with everything.

Yet Another Random String Generator

Date/Time Permalink: 03/28/08 09:36:26 am
Category: HOWTOs and Guides

I was browsing through the excellent Shell-Fu site and I ran across this simple random password generator. Handy, but a good candidate for aliasing since it's relatively long. Then, I figured why not make it a multi-function script?

So, here's what I call 'Randstring.sh':

#!/bin/bash

USAGESTRING="USAGE Randstring.sh l(letter),L(LETTER),n(number),a(all) N(length)\n \
             example: 'Randstring.sh n 8' returns random 8-digit number"

if [ "$1" ]; then
  ATRIB="$1"
else
  echo -e $USAGESTRING
  exit 1
fi
if [ "$2" ]; then
  LENGTH="$2"
else
  echo -e $USAGESTRING
  exit 1
fi

case $ATRIB in
  l) ATRIBSTRING="a-z" ;;
  L) ATRIBSTRING="A-Z" ;;
  n) ATRIBSTRING="0-9" ;;
  a) ATRIBSTRING="A-Za-z0-9" ;;
  *) echo -e $USAGESTRING
     exit 1 ;;
esac

case $LENGTH in
  [0-9]*) LENGTHARG=$LENGTH ;;
  *) echo -e $USAGESTRING
     exit 1 ;;
esac

echo $(cat /dev/urandom | tr -dc $ATRIBSTRING | head -c$LENGTHARG)

exit 0

I'm using a lot of argument-checking here. I might as well make something idiot-proof for a change - especially if I'm the idiot in question!

Anyway, calling it with...

  • "Randstring.sh L 8" will give you 8 UPPERCASE letters,
  • "Randstring.sh a 12" will give you 12 characters including Upper/lower letters and numbers,
  • "Randstring.sh n 16" will give a 16-digit random number,

and so on. Keep in mind with the numbers, there's no guarantee against having zeros at the beginning, so it might evaluate to a shorter number if you do anything mathy with it.

Follow me on Twitter for an update every time this blog gets a post.
Stumble it Reddit this share on Facebook

suddenly the moon