Ensuring new files in a directory belong to the group

67

19

I want to create a shared directory when a number of users (all belong to say mygroup) can create and edit files. I would like all files in this directory and subdirectory to belong to mygroup

I have changed existing files to have group mygroup using chgrp, but new files still get created belong to the user's primary group. Is there a way of ensuring new files belong to the group without repeatedly running chgrp.

justintime

Posted 2011-05-01T19:06:54.327

Reputation: 2 651

Answers

108

You want to set the SetGID bit.

chmod g+s dir

All new files created in the directory will have the group set to the group of the directory.

A superuser blog post explained the sticky bits and other Linux permission bits:

SetGID, however, is a whole different ball game. When a directory has the SetGID bit set and a file is created within that directory the group ownership of the file is automatically modified to be the group of the directory.

lesmana

Posted 2011-05-01T19:06:54.327

Reputation: 14 930

@LukePH's answer below is crucial to not being confused when this fails silently: use sudo – Rhubarb – 2018-01-18T14:44:28.417

@daaxix: To make sure that new subdirectories have the same permissions, use ACLs as described here: https://unix.stackexchange.com/a/12847/10030

– talljosh – 2020-02-06T04:04:03.567

1Thanks. The reference is useful. describes the umask command that is part of the picture – justintime – 2011-05-02T17:43:23.667

5What about creating a subdirectory in the initial directory which also belongs to the group of the parent directory? Is this possible? – daaxix – 2013-03-11T22:27:22.117

11

This might get a few people stuck with setgid, if the folder's group is different from your own you may need to run chmod as root but you won't get any error indicating you need to do this.

without sudo

$ ls -ld dir
drwxrwxr-x 2 luke testgroup 4096 Mar  9 10:44 dir

$ chmod g+s dir                                     # no errors

$ ls -ld dir
drwxrwxr-x 2 luke testgroup 4096 Mar  9 10:44 dir   # but nothing changed

$ touch dir/nosudo && ls -l dir/
-rw-rw-r-- 1 luke luke 0 Mar  9 10:51 nosudo        # and the group is set wrong

with sudo

$ sudo chmod g+s dir

$ ls -ld dir
drwxrwsr-x 2 luke testgroup 4096 Mar  9 10:44 dir   # the setgid bit is now on

$ touch dir/withsudo && ls -l dir/
-rw-rw-r-- 1 luke luke      0 Mar  9 10:51 nosudo
-rw-rw-r-- 1 luke testgroup 0 Mar  9 10:51 withsudo # and the group is set right

LukePH

Posted 2011-05-01T19:06:54.327

Reputation: 241

11

Set the setgid permission flag on the folders.

chmod g+s dirname

Daniel Beck

Posted 2011-05-01T19:06:54.327

Reputation: 98 421