chmod -R
Applies a change to a directory and everything inside it.
chmod -R mode dir walks the directory tree and applies the same change to every file and directory in it.
With a number that's usually wrong, because directories and files need different modes: chmod -R 755 marks every file executable, and chmod -R 644 takes the search bit off every directory, locking everyone out. Use a symbolic mode with capital X, or find.
Examples
chmod -R u+rwX,go+rX,go-w /var/www/site
755 for directories and 644 for files in one pass — capital X adds execute only to directories and files that are already executable
find /var/www/site -type d -exec chmod 755 {} +directories only
find /var/www/site -type f -exec chmod 644 {} +files only
chmod -R go-rwx ~/.ssh
a symbolic change is safe recursively: it only touches the bits it names
Good to know
- There's no undo. Before a big recursive change, save the current modes:
getfacl -R dir > perms.acllets you restore them withsetfacl --restore=perms.acl. - Never run
chmod -Ron/or a system directory. It breaks setuid programs like sudo, and ssh refuses keys whose permissions are too open. - GNU chmod changes the target of a symlink named on the command line, but ignores symlinks it meets while recursing.
- "Permission denied" errors after deploys are usually an ownership problem.
chown -Rto the right user fixes them without loosening permissions.
Frequently asked questions
How do I chmod only directories, or only files?
Use find: find dir -type d -exec chmod 755 {} + for directories and find dir -type f -exec chmod 644 {} + for files. Or use capital X in one pass: chmod -R u+rwX,go+rX,go-w dir.
What does capital X mean in chmod?
Execute only where it makes sense: on directories, and on files that already have execute permission for someone. It lets one recursive command make directories searchable without making plain files executable.
Is chmod -R 777 ever a good idea?
No. It gives every user write access to every file in the tree and marks all of them executable. Fix the owner with chown, or use a shared group with mode 2775 for directories.