Bash 脚本-如何设置用于创建新文件的组?

我正在执行一个 bash shell 脚本,我想更改创建新文件的默认组。我知道您使用 umask来更改权限。有什么给大家的吗?

63815 次浏览

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)

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.