Check if a user is in a group

后端 未结 13 1885
梦如初夏
梦如初夏 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:48

    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'
    

提交回复
热议问题