Check if a user is in a group

后端 未结 13 2082
梦如初夏
梦如初夏 2021-01-31 02:42

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

13条回答
  •  庸人自扰
    2021-01-31 02:57

    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 groupss 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.

提交回复
热议问题