Search code examples
unixshellsolariscsh

How do you use newgrp in a script then stay in that group when the script exits


I am running a script on a solaris Box. specifically SunOS 5.7. I am not root. I am trying to execute a script similar to the following:

newgrp thegroup << FOO
source .login_stuff
echo "hello world"
FOO

The Script runs. The problem is it returns back to the calling process which puts me in the old group with the source .login_stuff not being sourced. I understand this behavior. What I am looking for is a way to stay in the sub shell. Now I know I could put an xterm& (see below) in the script and that would do it, but having a new xterm is undesirable.

Passing your current pid as a parameter.

newgrp thegroup << FOO
source .login_stuff
xterm&
echo $1
kill -9 $1
FOO

I do not have sg available. Also, newgrp is necessary.


Solution

  • newgrp adm << ANYNAME
    # You can do more lines than just this.
    echo This is running as group \$(id -gn)
    ANYNAME
    

    ..will output:

    This is running as group adm
    

    Be careful -- Make sure you escape the '$' with a slash. The interactions are a little strange, because it expands even single-quotes before it executes the shell as the other group. so, if your primary group is 'users', and the group you're trying to use is 'adm', then:

    newgrp adm << END
    # You can do more lines than just this.
    echo 'This is running as group $(id -gn)'
    END
    

    ..will output:

    This is running as group users
    

    ..because 'id -gn' was run by the current shell, then sent to the one running as adm. Anyways, I know this post is ancient, but hope this is useful to someone.