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/passwdAn example of an /etc/passwd file:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
......
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
messagebus:x:103:106::/nonexistent:/usr/sbin/nologin
syslog:x:104:110::/home/syslog:/usr/sbin/nologin
......Each line contains information of one user which has 7 fields separated by colons (:):
- Username (e.g. systemd-network)
- Encrypted password (xrepresents that the password located in the/etc/shadowfile)
- 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-networkIf 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/passwdGet 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