Advertisement
theitd

chmodr

Sep 25th, 2013
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.91 KB | None | 0 0
  1. #!/bin/sh
  2. #
  3. # chmodr.sh
  4. #
  5. # author: Francis Byrne & The ITD
  6. # date: 2013/09/25
  7. #
  8. # Generic Script for recursively setting permissions for directories and files
  9. # to defined or default permissions using chmod.
  10. #
  11. # Takes a path to recurse through and options for specifying directory and/or
  12. # file permissions.
  13. # Outputs a list of affected directories and files.
  14. #
  15. # If no options are specified, it recursively resets all directory and file
  16. # permissions to the default for most OSs (dirs: 755, files: 644).
  17.  
  18. # ITD: Added support for no directory parameter (uses current dir if none specified)
  19. #
  20.  
  21. # Usage message
  22. usage()
  23. {
  24.   echo "Usage: $0 -d DIRPERMS -f FILEPERMS PATH"
  25.   echo "Arguments:"
  26.   echo "PATH: path to the root directory you wish to modify permissions for"
  27.   echo "Options:"
  28.   echo " -d DIRPERMS, directory permissions"
  29.   echo " -f FILEPERMS, file permissions"
  30.   exit 1
  31. }
  32.  
  33. # Check if user entered arguments
  34. if [ $# -lt 1 ] ; then
  35.  usage
  36. fi
  37.  
  38. # Set the directory path
  39. ROOT=$1;
  40. if [ -d $ROOT ] ; then
  41.     shift
  42. else
  43.     echo "Using current directory";
  44.     ROOT=".";
  45. fi
  46.  
  47. # Get options
  48. while getopts d:f: opt;
  49. do
  50.   case "$opt" in
  51.     d)  DIRPERMS="$OPTARG";
  52. ;;
  53.     f)  FILEPERMS="$OPTARG";
  54. ;;
  55.     \?) usage
  56. ;;
  57.   esac
  58. done
  59.  
  60. # Shift option index so that $1 now refers to the first argument
  61. shift $(($OPTIND - 1))
  62.  
  63. # Default directory and file permissions, if not set on command line
  64. if [ -z "$DIRPERMS" ] && [ -z "$FILEPERMS" ] ; then
  65.   DIRPERMS=755
  66.   FILEPERMS=644
  67. fi
  68.  
  69. # Check if the root path is a valid directory
  70. if [ ! -d $ROOT ] ; then
  71.  echo "$ROOT does not exist or isn't a directory!" ; exit 1
  72. fi
  73.  
  74. # Recursively set directory/file permissions based on the permission variables
  75. if [ -n "$DIRPERMS" ] ; then
  76.   find $ROOT -type d -print0 | xargs -0 chmod -v $DIRPERMS
  77. fi
  78.  
  79. if [ -n "$FILEPERMS" ] ; then
  80.   find $ROOT -type f -print0 | xargs -0 chmod -v $FILEPERMS
  81. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement