Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting bash newgrp functionality on startup

Tags:

bash

As a part of my setups, I often need, in our environements, to use

newgrp voodoo

If I try to put it in the .bashrc file, I get infinite loops.

Any ideas how to get the same functionality automatically loaded in startup?

like image 286
user1134991 Avatar asked Mar 28 '13 12:03

user1134991


2 Answers

There are 2 scripts that will get started once you start bash:

  • .bashrc for interactive shells

  • .bash_profile for login shells

Depending on the way you run the newgrp command one of them will be executed:

  • newgrp - your_group will start a new login shell and thus read .bash_profile

  • newgrp your_group (without the dash) will start a new interactive shell reading .bashrc

If you don't source one file from the other you should be able to circumvent the recursion by choosing the right combination of startup script and newgrp switch

  • newgrp - ... in .bashrc will work

  • newgrp ... in .bash_profile will work

The other two combinations will lead to the recursion you already described. If one of both files sources the other as it is often seen you'll be in trouble anyways.

BTW.: if .bash_profile doesn't exist bash will read the file .profile instead. I just mention it as some experts even manage to source their .bashrc from there.

If neither combination applies to your setup you might have to take resort to shell scripting instead. The environment variable $GROUPS should report the group you are member of, so something like:

[ "$GROUPS" = "200" ] || newgrp your_group

or whatever the id of your voodoo group is might help.

like image 90
mikyra Avatar answered Sep 22 '22 14:09

mikyra


You can check the current group id with the command id -gn, then call newgrp only if you aren't in the right group. So your .bashrc could include

# Switch groups, but only if necessary
if [[ `id -gn` != "mygroup" ]]
then
    newgrp mygroup
    exit
fi

Side note, this syntax also works for ksh.

like image 37
Jeremy Grim Avatar answered Sep 23 '22 14:09

Jeremy Grim