Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

randomman.sh

By: a guest on Jul 3rd, 2012  |  syntax: Bash  |  size: 0.78 KB  |  views: 1,054  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #!/bin/bash
  2. # Reads a given directory and picks a random file.
  3.  
  4. # The directory you want to use. You could use "$1" instead if you
  5. # wanted to parametrize it.
  6. DIR="/usr/share/man/man1"
  7. # DIR="$1"
  8.  
  9. # Internal Field Separator set to newline, so file names with
  10. # spaces do not break our script.
  11. IFS='
  12. '
  13.  
  14. if [[ -d "${DIR}" ]]
  15. then
  16.   # Runs ls on the given dir, and dumps the output into a matrix,
  17.   # it uses the new lines character as a field delimiter, as explained above.
  18.   file_matrix=($(ls "${DIR}"))
  19.   num_files=${#file_matrix[*]}
  20.   # This is the command you want to run on a random file.
  21.   # Change "ls -l" by anything you want, it's just an example.
  22.   man `echo "${file_matrix[$((RANDOM%num_files))]}" | gawk '{print substr( $0, 0, index($0, ".1.gz")-1 )}'`
  23. fi
  24.  
  25. exit 0