DevOps ToolChain, WikiPedia, CC BY-SA 4.0

A Script for Testing Membership in a Unix Group

Sometimes you just need a boolean test for a given question. In this post we’ll look at answering the question, “Is this user in a given group?” Seems simple enough.

It’s easy to see what groups a user is a member of in a shell:

% id$ id
uid=1068601116( gid=1068601115( groups=1068601115(,1068600513(domain,1068601109(linux,1068601118(application

Note that Alice is an Active Directory domain user. We want to test whether or not she is a member of the application group. We can see this with our eyes in the terminal, but a little scripting is in order. We’ll skip error checking for this first example.

Let’s take it out for a spin.$ ./ `whoami` "linux"
User IS NOT in group linux

Now let’s test whether or not Alice is in the application group:$ ./ `whoami` "application"
User IS in group application

Terrific. This will come in handy in the next blog post.

Let’s clean this up into a function that can be sourced in a script or shell:$ uig `whoami` "linux"$ echo $?

Or, the invocation we’re most likely to use:

Leave a Reply

Your email address will not be published. Required fields are marked *