FreeBSD: Commands to List All Users and Groups in the System


2 views

As a FreeBSD system administrator or developer, you'll often need to retrieve user and group information. Here are the essential commands and techniques:

The primary command to list users is:

cat /etc/passwd

This will display all users in the standard Unix password file format. For better readability, use:

cut -d: -f1 /etc/passwd

To filter out system accounts and only show regular users:

grep -vE '^.*:[*!]:' /etc/master.passwd | cut -d: -f1

To list all groups in the system:

cat /etc/group

For just the group names:

cut -d: -f1 /etc/group

FreeBSD provides several useful commands:

pw usershow
pw groupshow

For detailed information about a specific user:

id username

To create a nicely formatted list of users with their UIDs:

awk -F: '{ printf "%-20s %s\n", $1, $3 }' /etc/passwd

For groups with their GIDs:

awk -F: '{ printf "%-20s %s\n", $1, $3 }' /etc/group

If you have Python installed:

python -c "import pwd, grp; print('\n'.join(u[0] for u in pwd.getpwall()))"
python -c "import grp; print('\n'.join(g[0] for g in grp.getgrall()))"

To see which groups a user belongs to:

groups username

Or for the current user:

groups

To find users with UID ≥ 1000 (typically non-system users):

awk -F: '$3 >= 1000 {print $1}' /etc/passwd

To find groups with GID ≥ 1000:

awk -F: '$3 >= 1000 {print $1}' /etc/group

FreeBSD, like other Unix-like systems, manages user accounts and groups through several key files:

  • /etc/passwd - Contains user account information
  • /etc/group - Contains group definitions
  • /etc/master.passwd - The master password file (hashed passwords)

The simplest way to list all users is using the getent command:

getent passwd

For a cleaner output showing just usernames:

getent passwd | cut -d: -f1

Similarly, to list all groups:

getent group

Or for just group names:

getent group | cut -d: -f1

If getent isn't available, you can directly read the files:

cat /etc/passwd
cat /etc/group

To find users with login shells (excluding system accounts):

getent passwd | grep -v '/usr/sbin/nologin' | grep -v '/bin/false'

Here's a bash script to list users with their primary groups:

#!/bin/sh
getent passwd | while IFS=: read -r username password uid gid gecos home shell; do
    groupname=$(getent group "$gid" | cut -d: -f1)
    echo "User: $username (UID: $uid), Primary Group: $groupname (GID: $gid)"
done

FreeBSD's pw command provides additional control:

pw usershow -a   # List all users
pw groupshow -a  # List all groups

To see which groups a specific user belongs to:

id username
groups username

For systems with many users, consider these optimizations:

# Faster alternative for large user bases
awk -F: '{print $1}' /etc/passwd