Website Vidya
SecurityStep-by-Step Guide

Chmod Recursive in Linux: Change Permissions on Folders

Learn chmod recursive in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
Chmod Recursive in Linux: Change Permissions on Folders
AI Executive SummaryWebsiteVidya AI

10 min read

Learn chmod recursive in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What chmod Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Applying chmod recursive in linux systems allows administrators to modify discretionary file mode bits across entire directory hierarchies in a single operation. When deploying web applications, configuring shared team volumes, or preparing container filesystems, hundreds or thousands of nested files and subdirectories must conform to strict security baselines.

The native mechanism for recursive modification is the -R (or --recursive) flag provided by GNU chmod. When invoked, chmod traverses the directory tree depth-first, adjusting mode bits for every discovered filesystem node. However, naive usage of chmod -R often introduces critical security and usability issues by applying identical octal numbers indiscriminately to both regular files and directory containers.

Because directories require execute (x) permissions for traversal while regular files (HTML, PHP, JavaScript, images) should never be executable unless they are compiled binaries or scripts, mastering safe recursive permission workflows—including uppercase X and find -exec patterns—is essential for production systems.

Advertisement
Chmod Recursive in Linux: Change Permissions on Folders — syntax, flags, and practical terminal workflow diagram
Chmod Recursive in Linux: Change Permissions on Folders — command syntax, key options, and production workflow reference.

What chmod Does and When to Use It

When chmod -R executes, it utilizes standard directory traversal APIs (such as fts(3) or nftw(3)) to walk the filesystem hierarchy. For each encountered dentry, it issues a fchmodat(2) system call with the specified mode bits. If the user encounters a symbolic link during traversal, POSIX specifies that chmod does not alter permissions on the symbolic link itself (as symlink mode bits are ignored on Linux), but by default GNU chmod will either ignore symlinks or resolve their targets depending on options like -H, -L, or -P.

The fundamental conflict in recursive permissions arises from the dual meaning of the execute bit. On an ext4, XFS, or Btrfs filesystem, bit 00100 on an inode designates S_IXUSR. For a regular file, this bit tells the kernel that the file may be mapped into memory and executed via execve(2). For a directory inode, this same bit represents the search privilege, enabling path resolution (lookup) to access entries inside the folder. A blanket chmod -R 755 inappropriately marks text files executable, while chmod -R 644 strips directory search rights, making folders impossible to enter.

Linux enforces discretionary access control (DAC) by evaluating the effective User ID (EUID), effective Group ID (EGID), and supplementary groups against inode permission bits. When chmod executes, the Virtual File System (VFS) and active Linux Security Modules (SELinux or AppArmor) validate the caller's privileges before committing changes to disk or account databases.

Availability and Installation Across Linux Distributions

The chmod utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether chmod is installed and inspect which binary path and version your shell resolves:

type -a chmod
chmod --version 2>/dev/null || man -f chmod

# Illustrative output (reviewed against documentation)
chmod is /usr/bin/chmod
chmod (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

chmod -R [OPTION]... MODE DIRECTORY... | find DIRECTORY -type d -exec chmod 755 {} +

The standard syntax for recursive operation is chmod [OPTION]... -R MODE DIRECTORY.... The MODE parameter accepts either octal numeric notation (e.g., 755, 644) or symbolic expressions (e.g., u=rwX,go=rX). Key options that modify traversal behavior include -v (--verbose) to log every modified file, -c (--changes) to report only actual changes, and --preserve-root to prevent accidental execution against the root filesystem.

To resolve the directory vs. file execute dilemma symbolically, GNU chmod supports the special uppercase X permission flag. Writing chmod -R u=rwX,go=rX /path tells chmod to set the execute bit ONLY on directories, or on files that already possess an execute bit for at least one user class. Regular text files that were not executable remain non-executable (rw-r--r--), while directories receive full traversal rights (rwxr-xr-x).

  • 0 — All files and directories across the target hierarchy were successfully updated.
  • 1 — Minor operational failure, such as encountering files owned by other users without sufficient privileges.
  • 2 — Malformed command-line syntax, invalid mode argument, or missing directory operand.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-R--recursiveRecursively alter permissions across all subdirectories and contained files.
-c--changesVerbose output reporting only when a file's permission mode is actually modified.
-v--verboseOutputs a diagnostic line for every file and folder processed, regardless of change.
-f--silent, --quietSuppresses error messages for files that could not be modified due to permission constraints.
-H-HIf a command-line argument is a symbolic link to a directory, traverse it (only with -R).
-L-LTraverse every symbolic link to a directory encountered during recursive walk.
-P-PDo not traverse any symbolic links encountered during recursive walk (default behavior).
--preserve-root--preserve-rootFails safety check if operating recursively on the root filesystem ('/').

Using -c (--changes) instead of -v (--verbose) during large recursive permission updates is a crucial best practice on high-density storage volumes. When operating on an application tree containing 100,000 files, -v produces 100,000 lines of terminal output, flooding logs and consuming CPU cycles; -c emits output only for files whose mode bits actually changed.

Advertisement

Understanding symlink traversal options (-H, -L, -P) is equally important. By default (-P), chmod -R does not follow symbolic links inside the directory tree, protecting external directories from unintentional permission changes. If your deployment requires following symlinks explicitly, pass -L with caution.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Basic Recursive Permission Change with chmod -R

Apply recursive permissions across a project folder using standard octal notation.

mkdir -p /tmp/webapp/config && touch /tmp/webapp/index.php /tmp/webapp/config/db.ini
chmod -R 750 /tmp/webapp
stat -c "%a %n" /tmp/webapp /tmp/webapp/index.php /tmp/webapp/config

# Illustrative output (reviewed against documentation)
750 /tmp/webapp
750 /tmp/webapp/index.php
750 /tmp/webapp/config

The -R flag applies mode 750 to /tmp/webapp, the nested config folder, and both contained files.

2. Safe Recursive Permissions with Uppercase X

Set directories to 755 and regular files to 644 simultaneously using the symbolic uppercase X flag.

chmod -R u=rwX,go=rX /tmp/webapp
stat -c "%a %A %n" /tmp/webapp /tmp/webapp/config /tmp/webapp/index.php

# Illustrative output (reviewed against documentation)
755 drwxr-xr-x /tmp/webapp
755 drwxr-xr-x /tmp/webapp/config
644 -rw-r--r-- /tmp/webapp/index.php

Uppercase X evaluates inodes dynamically: directories receive execute (755), while plain text files receive read/write without execute (644).

3. Separate Recursive Permissions Using find for Files and Folders

The industry-standard sysadmin method to strictly set 755 on directories and 644 on files using find.

find /tmp/webapp -type d -exec chmod 755 {} +
find /tmp/webapp -type f -exec chmod 644 {} +
stat -c "%a %F %n" /tmp/webapp /tmp/webapp/index.php

# Illustrative output (reviewed against documentation)
755 directory /tmp/webapp
644 regular file /tmp/webapp/index.php

Using find -type d isolates directories for 755, while -type f isolates files for 644. The '+' delimiter optimizes execution by passing multiple arguments per invocation.

4. Audit and Log Actual Permission Changes with -c

Run recursive chmod while displaying only the files that required an actual permission update.

touch /tmp/webapp/new_file.txt && chmod 777 /tmp/webapp/new_file.txt
chmod -R -c 644 /tmp/webapp/*.txt

# Illustrative output (reviewed against documentation)
mode of '/tmp/webapp/new_file.txt' changed from 0777 (rwxrwxrwx) to 0644 (rw-r--r--)

The -c flag filters out unchanged files, making it ideal for auditing modifications in shell scripts.

5. Recursively Remove Write Access for Group and Others

Harden a directory tree by revoking write permissions from group and other users without altering read or execute.

chmod -R go-w /tmp/webapp
ls -la /tmp/webapp/config

# Illustrative output (reviewed against documentation)
drwxr-xr-x 2 admin admin 4096 Oct 22 20:35 .
drwxr-xr-x 3 admin admin 4096 Oct 22 20:35 ..
-rw-r--r-- 1 admin admin    0 Oct 22 20:35 db.ini

The symbolic operation go-w traverses all files and directories, stripping group and world write bits while leaving owner rights intact.

6. Using Reference Files for Recursive Permission Clones

Clone the permission mode of an established golden directory structure onto a newly extracted deployment.

mkdir -p /tmp/golden_dir && chmod 750 /tmp/golden_dir
chmod -R --reference=/tmp/golden_dir /tmp/webapp
stat -c "%a %n" /tmp/webapp /tmp/webapp/config

# Illustrative output (reviewed against documentation)
750 /tmp/webapp
750 /tmp/webapp/config

The --reference option copies the exact mode bits of /tmp/golden_dir recursively across all target nodes.

Real-World Workflows, Pipelines, and Shell Automation

WordPress and Web Application Deployment Permission Hardening

After deploying a web application (like WordPress, Laravel, or Node.js) under /var/www, securely configure permissions so directories are 755, files are 644, and special writable upload directories allow web server writes.

WEB_ROOT="/var/www/html/myproject"
WEB_USER="www-data"

echo "Setting ownership..."
sudo chown -R "${WEB_USER}:${WEB_USER}" "$WEB_ROOT"

echo "Applying directory 755 permissions..."
sudo find "$WEB_ROOT" -type d -exec chmod 755 {} +

echo "Applying regular file 644 permissions..."
sudo find "$WEB_ROOT" -type f -exec chmod 644 {} +

echo "Locking sensitive environment files..."
if [ -f "$WEB_ROOT/.env" ]; then
  sudo chmod 600 "$WEB_ROOT/.env"
fi

echo "Verification:"
ls -ld "$WEB_ROOT" && ls -l "$WEB_ROOT/.env" 2>/dev/null || true

# Illustrative output (reviewed against documentation)
Setting ownership...
Applying directory 755 permissions...
Applying regular file 644 permissions...
Locking sensitive environment files...
Verification:
drwxr-xr-x 4 www-data www-data 4096 Oct 22 20:36 /var/www/html/myproject
-rw------- 1 www-data www-data  420 Oct 22 20:36 /var/www/html/myproject/.env

This production workflow ensures that all web assets have minimal necessary privileges, while isolating database credentials in .env to mode 600.

Mass Security Remediation of Insecure World-Writable Files

Locate all world-writable files within a shared directory tree and recursively strip insecure write bits across the entire hierarchy.

TARGET_DIR="/srv/share"
echo "Scanning for insecure world-writable files in $TARGET_DIR..."
# Strip world write permissions from all items
sudo find "$TARGET_DIR" -perm -o+w -exec chmod o-w {} +
echo "Scan complete. Verifying zero world-writable files remain:"
sudo find "$TARGET_DIR" -perm -o+w

# Illustrative output (reviewed against documentation)
Scanning for insecure world-writable files in /srv/share...
Scan complete. Verifying zero world-writable files remain:

The -perm -o+w filter targets only objects possessing the other-write bit and strips it, remediating security findings without disturbing normal permissions.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding chmod inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Recursive chmod commands should never be combined with blanket 777 permissions. In web application hosting, granting 777 recursively allows attackers who compromise a web service to overwrite legitimate application source code, plant persistent webshells, and escalate privileges across the host.

Pay careful attention to SUID and SGID bits during recursive changes. Specifying an octal mode like chmod -R 0755 strips existing special bits (such as SGID on collaborative folders or SUID on helper binaries), while chmod -R 4755 would dangerously grant SUID execution across every file in the tree.

GNU/Linux, BSD, and BusyBox Implementation Differences

The -R flag is standardized in POSIX.1-2017 for chmod. However, symbolic uppercase 'X' is supported in GNU coreutils and BSD systems (macOS, FreeBSD), but may be missing in minimal BusyBox configurations.

On systems where uppercase X is unsupported or in scripts requiring strict POSIX compliance across minimal embedded appliances, always prefer the find command with -type d -exec chmod 755 {} + and -type f -exec chmod 644 {} +.

Troubleshooting Common Errors and Diagnostics

Directories became inaccessible after running chmod -R 644

Root Cause: Mode 644 stripped the execute (x) search bit from directories, preventing any user (even the owner) from entering folders or reading child files.

Resolution: Restore directory execute permissions recursively using uppercase X or find.

chmod -R u+X,go+X /path/to/dir
# Or using find:
find /path/to/dir -type d -exec chmod 755 {} +

chmod: changing permissions of 'file': Permission denied

Root Cause: The executing user is not the owner of the file and does not have superuser privileges.

Resolution: Prepend sudo to execute the command as root, or change ownership of the directory tree first with chown.

sudo chmod -R 755 /path/to/dir

Text files became unexpectedly executable after chmod -R 755

Root Cause: An octal mode of 755 was applied uniformly to both files and directories, activating execute bits on plain text files.

Resolution: Strip execute permissions from regular files while leaving directories intact using find.

find /path/to/dir -type f -exec chmod 644 {} +

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
chmod -R 777 gives all users on the system read, write, and execute permissions on every file and directory. This introduces severe security vulnerabilities, allowing any local user or compromised service to overwrite code, inject malware, or delete vital data.
The safest and most reliable command is: find /path -type d -exec chmod 755 {} + followed by find /path -type f -exec chmod 644 {} +. Alternatively, you can use the symbolic uppercase X flag: chmod -R u=rwX,go=rX /path.
No. By default, GNU chmod -R does not follow symbolic links encountered during recursive descent (equivalent to the -P flag). It will not modify the permissions of files or directories located outside the target directory via symlinks.
-v (verbose) prints a status line for every single file processed by chmod, even if its permissions were already correct. -c (changes) outputs a line only when an actual modification to the file's permission bits was made.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout