1753797 Members
7745 Online
108805 Solutions
New Discussion юеВ

scripting question

 
SOLVED
Go to solution

scripting question

How would I go about scripting the following:

IF $user IN group
THEN
FI

Where group is on of the groups in /etc/group?

Thanks in advance!
8 REPLIES 8
Charles McCary
Valued Contributor
Solution

Re: scripting question

Not sure what you're asking, but:

GROUP=dba
USER=michele

ISIT=`cat /etc/group | grep "^$GROUP:" | grep $USER`

if [ "${ISIT}" != '' ]
then

echo "$USER in $GROUP

else

echo "$USER not in $GROUP"

fi

S.K. Chan
Honored Contributor

Re: scripting question

Why bother ? You can use the "groups" command to find out which group a valid username belongs to. For example..
# groups -l skchan
will list all groups to which user "skchan" belongs to. Isn't that what you wanted ?
MANOJ SRIVASTAVA
Honored Contributor

Re: scripting question

You can try like this


export A=` cat /etc/group | grep $user | wc -l `

if [ $A = 1 ]
then

command

exit

fi

2nd command



Manoj Srivastava
Charles McCary
Valued Contributor

Re: scripting question

I agree, the group command is probably the easier way to go.
Jean-Luc Oudart
Honored Contributor

Re: scripting question

use the id -G or id -nG (as root) to get the group of a specific user

man id for more information

Jean-Luc
fiat lux
A. Clay Stephenson
Acclaimed Contributor

Re: scripting question

The groups command has one other advantage that you have overlooked. It will also work in an NIS and NIS+ environment as well as the vanilla /etc/group world.
If it ain't broke, I can fix that.
Darrell Allen
Honored Contributor

Re: scripting question

A couple of things to be aware of...

You will need to use "groups username" or "groups -g username" instead of "groups -l username" if you don't use /etc/logingroups.

If the user is not listed in /etc/group for his primary group (as specified in /etc/passwd), "groups -g" will not list the user's primary group. "groups" and "id -Gn" will list the user's primary group.

If you have su'ed to an account, "groups" without specifying the username will default to whom you logged in as, not the current username. "id -Gn" defaults to the current username.

Personally, I like:
id -Gn $user | grep groupname >/dev/null
if [ $? = 0 ]
then
echo is a member of the group
fi

Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)

Re: scripting question

Well, I needed something that I could put in a script to say if a user was in this group, do one thing and if not, skip it.

I've tried the "id -nG username" command and don't get any results, even if I use a username that I can clearly see in /etc/group as belonging to a group.

The cat /etc/group works for me. I guess I was thinking too complicated to not think of something so simple!

Thank you all for helping me with my mental block!

Michele