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

Paul picture Paul · Nov 18, 2008 · Viewed 18k times · Source

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.

Answer

plijnzaad picture plijnzaad · Sep 8, 2010

The following works nicely; put the following bit at the top of the (Bourne or Bash) script:

### first become another group
group=admin

if [ $(id -gn) != $group ]; then
  exec sg $group "$0 $*"
fi

### now continue with rest of the script

This works fine on Linuxen. One caveat: arguments containing spaces are broken apart. I suggest you use the env arg1='value 1' arg2='value 2' script.sh construct to pass them in (I couldn't get it to work with $@ for some reason)