Unix Command To Find All Users

How can I list out all the users in the system?

Answer

To list all users on a Unix system, even the ones who are not logged in, look at the /etc/password file.

$ cat /etc/passwd

Use the ‘cut’ command to only see one field from the password file.
 
 

For example, to just see the Unix user names, use the command “$ cat /etc/passwd | cut -d: -f1.”

$ cat /etc/passwd | cut -d: -f1

Or to only see the GECOS field (i.e. the account holder’s real name), try this:

$ cat /etc/passwd | cut -d: -f5

Note that users will also see Unix system accounts such as “root,” “bin,” and “daemon” in the /etc/passwd file. These system accounts are not Unix users.
 

List ALL users in a Unix Group (Primary and Secondary) 

Is there a command or better combination of cmds that will give me the list of Unix users in a particular Unix group?

Answer

If you have Python, an alternative

Code:

#!/usr/bin/env python

d={}

for line in open("/etc/group"):

    line=line.strip().split(":")

    users=line[3]

    if users:

        for u in users.split(","):

            d.setdefault(u,[])

            d[u].append(line[0])

for i,j in d.iteritems():

    print "%s is in groups: %s" %(i,j)

output
 

Code:

# ./test.py

daemon is in groups: ['bin']

user5 is in groups: ['dialout', 'video']

user2 is in groups: ['dialout', 'video']

user3 is in groups: ['dialout', 'video']

user1 is in groups: ['dialout', 'video']

nobody is in groups: ['nogroup']

Or

Code:

groupName="$1"

# Save some processing, no need to call getent so much.

#

groupEntry=$(getent group | grep "^${groupName}:")

if [ ! "$groupEntry" ]; then

        echo "Group $groupName does not exist." >&2

        exit 1

fi

# Note it IS possible that the same group is found in a local /etc/group

# as well as another source, you'll get two results.  We'll assume the

# first one wins.

#

groupId=$(echo "$groupEntry" | cut -d: -f3 | head -1)

# A username could be in a primary group and have that SAME primary

# group redundantly set as a secondary group.

#

passwdUser=$(getent passwd | cut -d: -f1,4 | grep ":${groupdId}$" | cut -d: -f1)

echo "${groupEntry},${passwdUser}" | cut -d: -f4 | tr ',' '\012' | sed '/^$/d' | sort -u

Unix Tips

See Also
Modify Etc Password File

Have a Unix Problem
Unix Forum - Do you have a UNIX Question?

Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books

Return to : - Unix System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.