How-to change ownership or file permissions recursively

How to change ownership or file permissions recursively

find is very useful for changing ownership or file permissions.

Note: Be careful use the echo check in every example. By removing echo the changes will take place! Examples are without guarantee!

Examples

set 644 to all regular files excluding hidden files

find /mnt/mytestfolder/ -type f \( ! -iname ".*" \)  -exec *echo* chmod 644 {} \;

set 755 to all regular files excluding hidden directories

find /mnt/mytestfolder/ -type d \( ! -iname ".*" \)  -exec *echo* chmod 755 {} \;

use “for” to change all file permissions excluding hidden file in all directories of current directory

for D in `find . -type d` ;do find "$D" -type f \( ! -iname ".*" \)  -exec *echo* "Would do chmod 644 {}" \; ;done

Attention! Stumbling blocks!

Now stumbling blocks are coming. Files or directories with spaces. This can be changed by setting the IFS (Internal Field Separator) variable, which is set to <space><tab><newline> by default. Before you do this you should save the current $IFS and reset it at the end.

Check with:

OIFS="$IFS";IFS=$'\n';for D in `find . -type d` ;do find "$D" -type f \( ! -iname ".*" \) -exec echo "Would do chmod 644 {}" \; ;done;IFS="$OIFS"

Exec the command with:

OIFS="$IFS";IFS=$'\n';for D in `find . -type d` ;do find "$D" -type f \( ! -iname ".*" \) -exec chmod 644 {} \; ;done;IFS="$OIFS"

Attention! We are talking about linux file permissions. If you use samba and windows clients, you need to adapt that to setfacl.

Mastodon