Check if an OS X user is an administrator?

In a script, how can I check if user "Bill" is a member of the admin group (group 80)?

I plan to use this in a script to check if he is and if he is not, make him an admin user.


Another way:

if groups username | grep -q -w admin; 
then 
    echo "Is admin"; 
else 
    echo "Not admin"; 
fi
  • groups username will show all username groups.
  • grep -q -w admin will search (without output -q) for word admin in the list of username groups.

As suggest by David Koontz, groups has been obsoleted by id utility. So, the if sentence should looks like the following to do the same:

if id -Gn username | grep -q -w admin;

See the man page for id.

id -G user 

will output a space delimited list of groups for a particular user. You'd have to detect 80 in the output list.


Here is a simple script to check if the user is in the admin group and if not adds him:

#!/bin/bash

echo "This script will add a non-admin user to the admin group"
echo "Please enter username"
read username
if groups $username | grep -q -w admin; 
    then 
        echo "User '$username' already is in the admin group"; 
    else 
        dscl . -append /Groups/admin GroupMembership $username;
    echo "User '$username' has been added to the admin group!"; 
    echo "Please restart your Mac to apply the changes."; 
fi

Save the script somewhere and make it executable by opening Terminal and entering:

chmod 755 /path/to/script

Run the script with sudo /path/to/script.

Since the default Mac admin of a server OS is a member of several admin groups (e.g. _lpadmin, access_bpf, _appserveradm etc) you might add them as well in the script.

Example:

add the following line to the script to add the user to the 'App Server Admins' group

 dscl . -append /Groups/_appserveradm GroupMembership $username;

To improve the script you might also add a condition to check if the entered user does exist at all.