How to create file as specific group

Solution 1:

sudo chgrp www-data *yourfile* will do it for individual files.

to do it for all files within a specific directory, change the group for that directory with the same command

sudo chgrp www-data /path/to/your/dir

then use the chmod command to make all files created within that directory belong to the group the directory belongs to with

sudo chmod g+s /path/to/your/dir

Solution 2:

The command sg can execute a command under a different group ID. If you are a member of the group newgroup, this should create newfile within that group :

sg newgroup "touch newfile"

(Source: https://unix.stackexchange.com/questions/18796/how-to-apply-changes-of-newly-added-user-groups-without-needing-to-reboot)

Solution 3:

We can create a simple function, based on touch and chown commands, which will create new empty files and will change their permissions simultaneously. Or when the file exists it just will change its permissions. For this purpose type in the terminal:

function touch-www { touch $1; chown $USER:www-data $1; }
export -f touch-www

Now we have a new command, called touch-www, and we can use it in this way:

touch-www /path/to/file

To be possible to use this new command everywhere in the file system let's modify the function in this way:

function touch-www { sudo touch $1; sudo chown $USER:www-data $1; }
export -f touch-www

Once the file have enough permissions we can edit it with the current user. So let's assume we want to use and nano in the way described here. Let's create new function:

function nano-www { sudo touch $1; sudo chown $USER:www-data $1; nano $1; }
export -f nano-www

To be these new commands permanently available we can add these lines in the bottom of the ~/.bashrc file:

function touch-www { sudo touch $1; sudo chown $USER:www-data $1; }
export -f touch-www

function nano-www { sudo touch $1; sudo chown $USER:www-data $1; nano $1; }
export -f nano-www