To change permissions for a directory and all its subfolders and files in Linux, use the chmod
command with the -R
(recursive) flag. Here’s how to do it:
1. Basic Syntax (Recursive Permission Change)
chmod -R <permissions> /path/to/directory
- Replace
<permissions>
with the desired numeric (e.g.,755
) or symbolic (e.g.,u=rwx,g=rx,o=rx
) mode. - Replace
/path/to/directory
with the target directory.
2. Example: Set 755
for Folders and 644
for Files
To differentiate between directories and files (recommended for security):
# Set directories to 755 (rwxr-xr-x)
find /path/to/directory -type d -exec chmod 755 {} \;
# Set files to 644 (rw-r--r--)
find /path/to/directory -type f -exec chmod 644 {} \;
3. Common Permission Scenarios
Goal | Command |
---|---|
Set 755 recursively | chmod -R 755 /path/to/directory |
Set 644 for files only | find /path -type f -exec chmod 644 {} \; |
Remove execute for all files | find /path -type f -exec chmod -x {} \; |
Grant full access (⚠️ unsafe) | chmod -R 777 /path/to/directory |
Understanding Permissions
Numeric Notation
7
=rwx
(read/write/execute)6
=rw-
(read/write)5
=r-x
(read/execute)4
=r--
(read)
Symbolic Notation
u
= user (owner)g
= groupo
= othersa
= all users+
/-
= add/remove permissions
Example (symbolic):
chmod -R a+rX /path/to/directory # Add read for all, execute for directories
Key Notes
- Execute (
x
): Directories requirex
to be accessible. Files only needx
if they are scripts/bins. - Security: Avoid
777
(full access for everyone) unless absolutely necessary. - Ownership: Use
chown -R
if you need to change ownership recursively (e.g.,chown -R user:group /path
).
Example Workflow
- Set default permissions for a web directory:
chmod -R 755 /var/www/html # Directories: rwxr-xr-x
find /var/www/html -type f -exec chmod 644 {} \; # Files: rw-r--r--
- Revoke write access for others:
chmod -R o-w /path/to/directory
Use these commands carefully, as incorrect permissions can expose your system to security risks!