Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a user is in a group

Tags:

bash

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.

like image 481
Gabi Barrientos Avatar asked Aug 25 '13 16:08

Gabi Barrientos


People also ask

How do you check if a user is a member of a group in Linux?

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

Which commands can display the groups of which a user is a member?

To display the members of a group, or the groups to which a user belongs, use the pts membership command. To display the groups that a user or group owns, use the pts listowned command. To display general information about a user or group, including its name, AFS ID, creator, and owner, use the pts examine command.

How do you check if a user exists in Linux?

user infomation is stored in /etc/passwd, so you can use "grep 'usename' /etc/passwd" to check if the username exist. meanwhile you can use "id" shell command, it will print the user id and group id, if the user does not exist, it will print "no such user" message.


2 Answers

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 
like image 100
Gilles Quenot Avatar answered Sep 27 '22 21:09

Gilles Quenot


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.
like image 27
Antxon Avatar answered Sep 27 '22 23:09

Antxon