3

I need to set the same permissions of owner to group recursively to all elements in a directory.

  • Only for rwx? Or also for s? (note that s has a different meaning for user/group and regular/directory files). – Stéphane Chazelas Mar 17 '15 at 11:41
1

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 set rwxXst, or a single letter from the set ugo.  …

                ︙

The letters rwxXst select ….  Instead of one or more of these letters, you can specify exactly one of the letters ugo: 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 RHEL 6 it's documented in: info coreutils 'Symbolic modes' – jxlxkcyx Mar 19 '15 at 14:39
1

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
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.