Advertisement
flipje

random_string_generator

Mar 9th, 2012
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.83 KB | None | 0 0
  1. #!/bin/bash
  2. # +-----------------------------------------------------------------------------------------+
  3. # | Bash random string generator                                                            |
  4. # | Handy for passwords or keys                                                             |
  5. # |                                                                                         |
  6. # |                                                                                         |
  7. # | November 2011 flip hess flip@nerdmetbril.nl                                             |
  8. # +-----------------------------------------------------------------------------------------+
  9.  
  10. # Global variables:
  11.  
  12. PATH='/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin'
  13. SCRIPT_PATH="${0}"
  14. ARGS="${#}"
  15. CHARSET="A-Za-z0-9!@\#\$%^&*\(\)_+=-[]><~}{"
  16. # CHARSET="[A-Za-z0-9]"
  17. # CHARSET="[A-Za-z]"
  18. # CHARSET="[0-9]
  19.  
  20.  
  21. # Functions:
  22.  
  23.   # exit function
  24.   function die()
  25.   {
  26.     echo "${1}"
  27.     exit 1
  28.   }
  29.  
  30.   # Shows usage function.
  31.   function fShowUsage()
  32.   {
  33.     echo -e "\n\
  34.    Usage: ${SCRIPT_PATH} <total chars>\n\
  35.         Create a set string of random characters
  36.         Handy for passwords, keys etc.
  37.         November 2011 flip@nerdmetbril.nl\n\
  38.    "
  39.  
  40.     return 0
  41.   }
  42.  
  43.   # Create random string
  44.   function fRandom()
  45.   {
  46.    local LENGTH="${1}"
  47.  
  48.    # check for arguments:
  49.    [ ${#} = 1 ] || { fShowUsage ; exit 1; }
  50.    
  51.    # check if arg only contains numbers:  
  52.    CHECK=$( echo ${LENGTH} | tr -d "[0-9]")
  53.    [ -z ${CHECK} ] || { fShowUsage ; exit 1; }
  54.  
  55.    # GENERATE STRING
  56.    PASS="$( < /dev/urandom tr -dc "${CHARSET}" | head -c "${LENGTH}" )"
  57.    
  58.    # Output
  59.    echo -e "Your ${LENGTH} characters string is:\n ${PASS}"
  60. }
  61.  
  62.  # Start the program:
  63.   fRandom "${@}"
  64.  
  65.  # Exit with previous return code:
  66.   exit "${?}"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement