Problem while running "newgrp" command in script

12,505

Solution 1

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:

#!/bin/ksh

echo "Before newgrp"
/usr/bin/newgrp users <<EONG
echo "hello from within newgrp"
id
EONG
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.

Solution 2

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
/path/to/script

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).

Share:
12,505

Related videos on Youtube

chanchal1987
Author by

chanchal1987

Now working in a Unix platform. Wanna get &amp; share knowledge of Unix from/with others... Badge:

Updated on September 18, 2022

Comments

  • chanchal1987
    chanchal1987 almost 2 years

    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?

    #/bin/ksh
    ...
    newgrp test_grp1
    ...
    

    Note: I am using Unix AIX OS.

  • tcoolspy
    tcoolspy almost 13 years
    Is there any reason this couldn't be done by wrapping the second half of the script in a subshell?
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' almost 13 years
    @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.
  • toing_toing
    toing_toing over 4 years
    love from me, saved the day using newgrp docker
  • toing_toing
    toing_toing over 4 years
    just a note that, the closing EONG should not be indented