Check if a user is in a group

2020-05-14 14:14发布

I have a server running where I use php to run a bash script to verify certain information of a user. For example, I have a webhosting server set up, and in order to be able to add another domain to their account I want to verify if the user is actually a member of the 'customers' group. What would be the best way to do this?

I have searched google, but all it comes up with is ways to check whether a user or a group exists, so google is not being a big help right now.

标签: bash
12条回答
Melony?
2楼-- · 2020-05-14 14:19

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
查看更多
Animai°情兽
3楼-- · 2020-05-14 14:19

Using the zero delimiter to split by lines:

id -nGz user | tr '\0' '\n' | grep '^group$'
查看更多
Bombasti
4楼-- · 2020-05-14 14:20

My version not relying on grep.

First parameter (mandatory): group
Second parameter (optional, defaults to current user)

isInGroup(){
   group="$1"
   user="${2:-$(whoami)}"
   ret=false 
   for x in $(groups "$user" |sed "s/.*://g")
   do [[ "$x" == "$group" ]] && { ret=true ; break ; }
   done
   eval "$ret"
}
查看更多
放我归山
5楼-- · 2020-05-14 14:21

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
查看更多
ゆ 、 Hurt°
6楼-- · 2020-05-14 14:22
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.
查看更多
甜甜的少女心
7楼-- · 2020-05-14 14:22
username='myuser'
if groups "$username" | grep -q -E ' customers(\s|$)'; then
    echo 'yes'
else
    echo 'no'
fi

I have to clear one thing: groups will probably return something like this:

myuser : cdrom floppy sudo audio dip video plugdev fuse

But there is one cornercase when your user is named customers:

customers : cdrom floppy sudo audio dip video plugdev fuse

For example, \bcustomers\b pattern is going to find the username, not the group. So you have to make sure that it is not the first word in the output.

Also, another good regexp is:

grep -q ' customers\b'
查看更多
登录 后发表回答