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
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'
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
Using the zero delimiter to split by lines:
id -nGz user | tr '\0' '\n' | grep '^group$'
if id -nG "$USER" | grep -qw "$GROUP"; then
echo $USER belongs to $GROUP
else
echo $USER does not belong to $GROUP
fi
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.For all those golf fans out there:
ingroup(){ [[ " "`id -Gn $2`" " == *" $1 "* ]] }
Usage: ingroup group [user]
Example:
if ingroup video; then
echo 'Enjoy the show!'
fi
This solution uses groups
so it gets stung if the username is returned as part of its output, which it wasn't on my system, there's no accounting for taste! (Note that a user is often part of a group with the same name as the user, so it probably doesn't matter anyway.) You could try: [[ `id -Gn $2`" " == *" $1 "* ]]
which won't look at the first word in groups
s output. Anything more complicated than that and we'd be over par.
TL;DR The point is I have taken advantage of the built in globbing in order to find the substring.
Edit: Thanks to @Anthony Geoghegan for the id -Gn
tip.
Sounds like an another answer:
username='myuser'
if grep -q -E "^customers:.*[:,]$username(,.*|\b)" /etc/group; then
echo 'true'
else
echo 'false'
fi
As reported by sputnick
the output of the groups
command may depend on your OS.
I am not sure how this code is going to perform, but most probably it will do better.