Check if a user is in a group

Solution 1:

Try doing this :

username=ANY_USERNAME
if getent group customers | grep -q "\b${username}\b"; then
    echo true
else
    echo false
fi

or

username=ANY_USERNAME
if groups $username | grep -q '\bcustomers\b'; then
    echo true
else
    echo false
fi

Solution 2:

if id -nG "$USER" | grep -qw "$GROUP"; then
    echo $USER belongs to $GROUP
else
    echo $USER does not belong to $GROUP
fi

Explanation:

  1. id -nG $USER shows the group names a user belongs to.
  2. grep -qw $GROUP checks silently if $GROUP as a whole word is present in the input.

Solution 3:

A slightly more error-proof method to check for group membership using zero char delimited fixed string grep.

if id -nGz "$USER" | grep -qzxF "$GROUP"
then
    echo User \`$USER\' belongs to group \`$GROUP\'
else
    echo User \`$USER\' does not belong to group \`$GROUP\'
fi

or using long opts

if id --name --groups --zero "$USER" | 
   grep --quiet --null-data --line-regexp --fixed-strings "$GROUP"
then
    echo User \`$USER\' belongs to group \`$GROUP\'
else
    echo User \`$USER\' does not belong to group \`$GROUP\'
fi

Solution 4:

I know this is probably old thread but just in case this also works well:

id -Gn "username"|grep -c "groupname"

if any number > 0 is returned then user is a member of that group.

Solution 5:

You could use groups $username_here | grep -q '\busergroup\b'

The exitcode will be 0 if a match was found, 1 if no match was found.

user_in_group()
{
    groups $1 | grep -q "\b$2\b"
}

you could use this function as user_in_group userfoo groupbar