Skip to content

Instantly share code, notes, and snippets.

@mparker17
Last active August 29, 2015 14:02
Show Gist options
  • Save mparker17/7135f92d8d29865a9bfc to your computer and use it in GitHub Desktop.
Save mparker17/7135f92d8d29865a9bfc to your computer and use it in GitHub Desktop.
Painlessly setting the mode of files / folders in a tree.
#!/bin/bash
#
# POSIX permissions for a folder need to include the execute bit so you can list
# their contents. But you don't want the execute flag on files, otherwise
# someone could try to run them like a program.
#
# For this reason,
#
# chmod -R $some_mode $path_to_folder
#
# is generally a bad idea.
#
# See http://en.wikipedia.org/wiki/File_system_permissions#Notation_of_traditional_Unix_permissions
# for more.
#
# Fortunately find(1) is pretty powerful and can save you a lot of time...
# To change the permissions of all directories in a folder and all sub-folders
# to $dir_perms (i.e.: 755 or u=rwx,og=rx):
find $path_to_folder -depth -type d -exec chmod $dir_perms '{}' \;
# ... literally, "Find all directories in $path_to_folder (including
# $path_to_folder) in depth-first order and, for each directory, execute
# `chmod $dir_perms` on it.
#
# If I remember correctly, depth-first order helps avoid errors when you have
# read-and-write-but-not-execute permissions to a set of nested folders. But I
# could be wrong.
#
# To change the permissions of all files in a folder and all sub-folders to
# $file_perms (i.e.: 644 or u=rw,og=r):
find $path_to_folder -type f -exec chmod $file_perms '{}' \;
# ... literally, "Find all files in $path_to_folder and, for each file, execute
# `chmod $file_perms` on it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment