I want to change the working group in my script. So I wrote a line newgrp test_grp1 in my script. But my script is automatically exited after running this line. Are there any solution to overcome this problem?

newgrp test_grp1

Note: I am using Unix AIX OS.

2 Answers 2


newgrp starts a subshell with the group you specified. So that line in your script will not finish until that subshell is done.

The handling of newgrp is also different if you're using bash or ksh. ksh implements it as a built-in command that is equivalent to exec /usr/bin/newgrp [group]. So, like exec, newgrp never returns. (See some documentation here.)

If you want it to return, and want to execute commands in that subshell with changed group identity, you can use redirection.

For example:


echo "Before newgrp"
/usr/bin/newgrp users <<EONG
echo "hello from within newgrp"
echo "After newgrp"

Notice: /usr/bin/newgrp is called explicitly to avoid the implicit exec from ksh. The last command in that script will run within the original shell, with the original group identity.

  • 3
    love from me, saved the day using newgrp docker Nov 27, 2019 at 16:38
  • 1
    just a note that, the closing EONG should not be indented Nov 27, 2019 at 16:48

Once a process has been started, it cannot gain any extra privileges. So you can't gain a group membership in the middle of a script. You can run the whole script with the extra group membership:

newgrp test_grp1

You can't change your real GID mid-script. If you really need that, switch to a language where you can, such as Perl. It's rare to need to change your real GID though, since it doesn't matter much. Usually it's enough to make the occasional call to chgrp (create files with no group permissions first, then run chgrp, then add group permissions; if you create files with group permissions, there's a race condition: a user who is in the first group could open the file before you have time to run chgrp).

  • Is there any reason this couldn't be done by wrapping the second half of the script in a subshell?
    – Caleb
    Aug 17, 2011 at 11:44
  • @Caleb Not a subshell strictly speaking, but you can pass a script to the shell invoked by newgrp on its standard input, as in Mat's answer. Aug 17, 2011 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.