I need to set the same permissions of owner to group recursively to all elements in a directory.
There's a fairly simple answer (although I don't know for sure whether it works on all versions of *nix); simply do
chmod g=u *
i.e., set the group permissions equal to the user permissions.
This is documented in chmod(1):
The format of a symbolic mode is [
ugoa
...][[+-=
][perms...]...], where perms is either zero or more letters from the setrwxXst
, or a single letter from the setugo
. …︙
The letters
rwxXst
select …. Instead of one or more of these letters, you can specify exactly one of the lettersugo
: the permissions granted to the user who owns the file (u
), the permissions granted to other users who are members of the file’s group (g
), and the permissions granted to users that are in neither of the two preceding categories (o
).
On a (recent for sed
's -z
) GNU system, you could do something like:
find . ! -type l -printf '%m:%p\0' |
sed -Ez '/^.?(.)\1.:/d;s/(.)(.)(.):/\1\1\2\x0/' |
xargs -r0n2 echo chmod
(remove echo
when satisfied with the result).
Note that it only addresses the r
, w
, x
bits not the special ones.
If you don't want it recursive:
find . -mindepth 1 -maxdepth 1 ! -type l -printf '%m:%p\0' |
sed -Ez '/^.?(.)\1.:/d;s/(.)(.)(.):/\1\1\2\x0/' |
xargs -r0n2 echo chmod
Try this:
for file in $(find .); do
perm=$(stat -c "%a" ${file});
echo chmod ${perm:0:1}${perm:0:1}${perm:2:1} ${file};
done
Remember to remove echo
.
Improved version:
find . -exec sh -c 'for file do
perm=$(stat -Lc "%a" "$file")
echo chmod "${perm:0:1}${perm:0:1}${perm:2:1}" "$file"
done' sh {} +
As in Stéphane Chazelas's answer,
- Use
-mindepth 1
to avoid processing.
. - Use
-maxdepth 1
to avoid recursion (entering subdirectories). - Use
! -type l
to avoid processing symbolic links (although this answer will handle symbolic links OK).
Note that this command will not work correctly for files that have any of the high-order mode bits (setuid, setgid, and sticky) set.
rwx
? Or also fors
? (note thats
has a different meaning for user/group and regular/directory files). – Stéphane Chazelas Mar 17 '15 at 11:41