Check if a user is in a group

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

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

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.

Tags:

Bash