Get List of Users in Linux

Get List of Users in Linux

When working with Linux system as a administrator, we might want to get a list of all users in the system or to count the number of users. This tutorial explains how to do that.

Commands have been tested on Ubuntu 20.04 LTS.

Get list of users

The /etc/passwd is a text file which stores details about local users in Linux system. We can view this file by using cat command:

cat /etc/passwd

An example of an /etc/passwd file:

systemd-network:x:100:102:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
systemd-timesync:x:102:104:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin

Each line contains information of one user which has 7 fields separated by colons (:):

  • Username (e.g. systemd-network)
  • Encrypted password (x represents that the password located in the /etc/shadow file)
  • UID - user ID number (e.g. 100)
  • GID - primary group ID number (e.g. 102)
  • GECOS - is a comma-separated list which may include full name of the user, telephone number, or other contact information (e.g. systemd Network Management,,,)
  • User home directory (e.g. /run/systemd)
  • Login shell (e.g. /usr/sbin/nologin)

Check if user exists

Using /etc/passwd file we can perform various operations. We can check whether a user exists in Linux system using the following command:

cat /etc/passwd | grep -w systemd-network

If the user exists, the command will print information of the user. No output means that user doesn't exist.

Get only usernames

Using cut command we can print selected fields of each line of a file. The following command prints only the first field which contains the username:

cut -d: -f1 /etc/passwd

Get the number of users

The wc command allows to count the number of lines in a file. The following command prints the number of users in the system:

cat /etc/passwd | wc -l

Leave a Comment

Cancel reply

Your email address will not be published.