Bash Scripting - How to set the group that new files will be created with? Bash Scripting - How to set the group that new files will be created with? unix unix

Bash Scripting - How to set the group that new files will be created with?


There are a couple ways to do this:

  1. You can change the default group for all files created in a particulardirectory by setting the setgid flag on the directory (chmod g+s _dir_).New files in the directory will then be created with the group of thedirectory (set using chgrp <group> <dir>). This applies to any programthat creates files in the directory.

    Note that this is automagically inherited for new subdirectories (as ofLinux 3.10), however, if sub-directories were already present, this changewon't be applied to them (use the -R flag for that).

  2. If the setgid flag is not set, then the default group will be set to the currentgroup id of the creating process. Although this can be set using the newgrpcommand, that creates a new shell that is difficult to use within a shellscript. If you want to execute a particular command (or set of commands)with the changed group, use the command sg <group> <command>.

    sg is not a POSIX standard command but is available on Linux.


The newgrp command is used to change the current group ID during a login session.

New directories created in that session will have the group ID set by the command.

newgrp(1)