How to make a random key using bash shell script

Command line Below is an example shell script that creates a random alphanumeric string. It does not use awk or sed, as I was working on a locked down server at the time.

The Code

#!/bin/bash

# Variables

ALPHANUM='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

CHARACTERS="$ALPHANUM"
CHARLENGTH=${#CHARACTERS}
KEY=''
KEYLENGTH=0

# makekey(): Return random key as string of a specified length

function makekey () {

 KEY=''
 COUNTER=0
 LENGTH=$1

 if [ "${LENGTH}" > 0 ] ; then
  while [ $COUNTER -lt $LENGTH ]; do

   #increment counter
   COUNTER=$(( $COUNTER + 1 ))

   # random number less than length of characters,
   # add character in that position to end of key
   ARBITRARY=$RANDOM
   LOCATION=$(( ARBITRARY %= CHARLENGTH ))
   NEWCHAR="${CHARACTERS:$LOCATION:1}"

   #append character at random location to string
   KEY="${KEY}${NEWCHAR}"

  done

 else
  echo "Insufficient length ( ${LENGTH} ) for makekey function"
  exit

 fi

}

# User enters length of key

read -p "
 How long do you want your key to be?
=" KEYLENGTH

 makekey "$KEYLENGTH"
 echo "Your random key is:
$KEY"

For More Information