-
-
Save itoffshore/a281c209c7b1b67dcc7b to your computer and use it in GitHub Desktop.
BASH Script to recursively set directory / file permissions & ownership
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# chmodr.sh | |
# | |
# Original Author: Francis Byrne | |
# date: 2011/02/12 | |
# | |
# Modified Script for recursively setting permissions & ownership for directories | |
# and files to defined or default permissions using chmod & chown. | |
# | |
# If no options are specified, it recursively resets all directory and file | |
# permissions to the default for most OSs (dirs: 755, files: 644). File & directory | |
# ownership is set recursively to the user running the script (unless set with -u -g). | |
# | |
usage() | |
{ | |
echo "Usage: $0 PATH -d DIRPERMS -f FILEPERMS -u USERPERMS -g GROUPPERMS" | |
echo "Arguments:" | |
echo "PATH: path to the root directory you wish to modify permissions for" | |
echo "Options:" | |
echo " -d DIRPERMS, directory permissions" | |
echo " -f FILEPERMS, file permissions" | |
echo " -u USERPERMS, user permissions" | |
echo " -g GROUPPERMS, group permissions" | |
echo " -h | -? this help message" | |
exit 1 | |
} | |
# Check if user entered arguments | |
if [ $# -lt 1 ] ; then | |
usage | |
fi | |
while getopts "d:f:u:g:h" flag | |
do | |
case "$flag" in | |
d) DIRPERMS="$OPTARG";; | |
f) FILEPERMS="$OPTARG";; | |
u) USERPERMS="$OPTARG";; | |
g) GROUPPERMS="$OPTARG";; | |
h) usage;; | |
\?) usage;; | |
esac | |
done | |
# Shift option index so that $1 now refers to the first argument | |
shift $(($OPTIND - 1)) | |
# Default directory and file permissions, if not set on command line | |
if [ -z "$DIRPERMS" ] && [ -z "$FILEPERMS" ] ; then | |
DIRPERMS=755 | |
FILEPERMS=644 | |
fi | |
# Default user / group if not set on the command line | |
if [ -z "$USERPERMS" ] && [ -z "$GROUPPERMS" ] ; then | |
USERPERMS=$USER | |
GROUPPERMS=$USER | |
fi | |
# Set the root path to be the argument entered by the user | |
ROOT=$1 | |
# Check if the root path is a valid directory | |
if [ ! -d $ROOT ] ; then | |
echo "$ROOT does not exist or isn't a directory !" ; exit 1 | |
fi | |
# Recursively set directory/file permissions based on the permission variables | |
if [ -n "$DIRPERMS" ] ; then | |
find $ROOT -type d -print0 | xargs -0 chmod -v $DIRPERMS | |
fi | |
if [ -n "$FILEPERMS" ] ; then | |
find $ROOT -type f -print0 | xargs -0 chmod -v $FILEPERMS | |
fi | |
# Recursively set user:group permissions | |
chown -Rv $USERPERMS:$GROUPPERMS $ROOT |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment