Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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.

share|improve this answer
    
Thanks. It is working... –  chanchal1987 Aug 17 '11 at 11:44

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|improve this answer
    
Is there any reason this couldn't be done by wrapping the second half of the script in a subshell? –  Caleb Aug 17 '11 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. –  Gilles Aug 17 '11 at 12:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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