Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to check to see if user X is a member of group Y in BASH on Linux without using getent?

Tags:

bash

To clarify:

getent group | grep someGroup | grep someUser

Problem: This dumps the entire group db, which might be attached to LDAP, etc., in an enterprise environment, and then filters them with grep to see if the user is there in someGroup.

So that's all groups, everywhere. Ouch.

Furthermore, administrative commands are often set to something that makes them completely unusable for anyone but an administrator. Even for a simple "Hey, is he a member of that group?" type query. Can't use the if [ -f -d etc...] commands because I'm doing it preparatory to a sodu -u someUser execution. This is to say that the script isn't running as the user in question.

Question: Is there a better way?

like image 459
user447607 Avatar asked Dec 26 '22 19:12

user447607


2 Answers

If you know both the username and group (as you appear to), you can use id like so:

id -Gn username | grep '\bgroupname\b'

id -Gn will display all group names a user is a member of, then grep will return 0 if the group is present or 1 if not. \b matches only on word boundaries, which keeps you from matching substrings of group names (e.g. every for everyone).

I believe id is available on all Unix and Unix-like systems. It's certainly present and functions the same way on Linux, OS X, and OpenBSD. However, \b does not work on the latter, since it is using BSD grep instead of GNU grep—alternative patterns are required.

like image 174
zigg Avatar answered May 23 '23 15:05

zigg


You could try using groups myUser which prints the groups a user is in, and then see if the list has your desired group.

like image 39
Morfic Avatar answered May 23 '23 17:05

Morfic