How do I change permissions for a folder and its subfolders/files in Linux?

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

GoalCommand
Set 755 recursivelychmod -R 755 /path/to/directory
Set 644 for files onlyfind /path -type f -exec chmod 644 {} \;
Remove execute for all filesfind /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 = group
  • o = others
  • a = 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 require x to be accessible. Files only need x 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

  1. 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--
  1. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *