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?
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.
You could try using groups myUser
which prints the groups a user is in, and then see if the list has your desired group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With