2

I want to execute one command and I want that it is executed with a specific groupname, that I'm belonging to, but which is not my default group. So all files created will belong to that group. Is there a command for that?

There is chgrp to fix it afterwards.

Then I found newgrp (Changing my default primary GID for every login session), but that creates a subshell. Thus a oneliner newgroup <groupname> && cmd does not work. And the shell needs to be closed later.

Both approaches looks error prone.

2

1 Answer 1

3

The command sg can be used for this purpose.

Citing man sg

sg [-] [group [-c ] command]

The sg command works similar to newgrp but accepts a command. The command will be executed with the /bin/sh shell. With most shells you may run sg from, you need to enclose multi-word commands in quotes. Another difference between newgrp and sg is that some shells treat newgrp specially, replacing themselves with a new instance of a shell that newgrp creates. This doesn't happen with sg, so upon exit from a sg command, you are returned to your previous group ID.


If you want to change the GID for multiple commands in a bash script, split the script in two and call the second script with sg or let the script call itself with sg and some arguments to avoid endless recursion.

In Python, there might be other ways to use the setgit system call.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .