CHMOD Directories or Files Only

When you need to modify file permissions recursively in a directory, you can use the chmod command along with the find command in Linux. Here are some commonly used commands to give different permissions to directories and files:

Recursively Give Directories Read & Execute Privileges

To recursively give directories read and execute privileges (755), you can use the following command:

1
find /path/to/base/dir -type d -exec chmod 755 {} +

This command finds all directories under /path/to/base/dir and sets their permissions to 755, which allows read and execute access for the owner, group, and others.

Alternatively, if there are many objects to process and you want to avoid spawning multiple chmod processes, you can use this command:

1
chmod 755 $(find /path/to/base/dir -type d)

This command finds all directories and sets their permissions in a single chmod operation.

Recursively Give Files Read Privileges

To recursively give files read privileges (644), you can use the following command:

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

This command finds all files under /path/to/base/dir and sets their permissions to 644, which allows read access for the owner and read-only access for the group and others.

Again, if you have many files to process and want to optimize the command, you can use:

1
chmod 644 $(find /path/to/base/dir -type f)

This command finds all files and sets their permissions in a single chmod operation.

Alternative Approach to Reduce chmod Spawning

If you want to further reduce the spawning of chmod processes and handle filenames with spaces or special characters correctly, you can use the xargs command with the -0 option, which handles null-terminated strings. Here’s how to do it:

For Directories

1
find /path/to/base/dir -type d -print0 | xargs -0 chmod 755

For Files

1
find /path/to/base/dir -type f -print0 | xargs -0 chmod 644

This approach is more efficient when dealing with a large number of files or directories and ensures that filenames with spaces or special characters are handled correctly.

0%