Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm doing a bash shell script and I want to change the default group that new files are created as. I know you use umask to change the permissions. Is there something for the group?

like image 439
Amandasaurus Avatar asked Aug 24 '09 08:08

Amandasaurus


People also ask

How to set primary group of directory in Linux?

To change the primary group a user is assigned to, run the usermod command, replacing examplegroup with the name of the group you want to be the primary and exampleusername with the name of the user account.

What are the sequence of commands for creating a new file and a new directory in Unix like environment?

cp [old] [new] copies a file. mkdir [path] creates a new directory. mv [old] [new] moves (renames) a file or directory. rm [path] removes (deletes) a file.

How do you create a new directory in bash?

Create a New Directory ( mkdir ) The first step in creating a new directory is to navigate to the directory that you would like to be the parent directory to this new directory using cd . Then, use the command mkdir followed by the name you would like to give the new directory (e.g. mkdir directory-name ).


1 Answers

There are a couple ways to do this:

  1. You can change the default group for all files created in a particular directory 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 the directory (set using chgrp <group> <dir>). This applies to any program that creates files in the directory.

    Note that this is automagically inherited for new subdirectories (as of Linux 3.10). However, if subdirectories were already present, this change won't be applied to them. Assuming that the subdirectories already have the correct group, the setgid flag can be added to them with: find . -type d -exec chmod g+s {} \; (suggested by Maciej Krawczyk in the comments)

  2. If the setgid flag is not set, then the default group will be set to the current group id of the creating process. Although this can be set using the newgrp command, that creates a new shell that is difficult to use within a shell script. 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.

like image 121
mark4o Avatar answered Oct 20 '22 00:10

mark4o