Unix / Linux: Get List of Usernames from /etc/passwd

Objective: Get the list of usernames defined in the /etc/passwd file.

The /etc/passwd file stores the account information (except the password field) of all local users on a Unix / Linux system. The password is normally stored in the /etc/shadow file.

The /etc/passwd file is world-readable. In other words, the file permissions allow anyone to read the file. A sample entry on the /etc/passwd file looks like this.

ibrahim:x:1000:50:Mohamed Ibrahim:/home/ibrahim:/bin/bash

Each account occupies one line and the field entries for every user are separated by a colon (“:”). There are 7 fields per line (or per user) and first field contains the username.

To extract the list of usernames, we can use one of the following commands.

$ awk -F':' '{print $1}' < /etc/passwd
$ sed 's/:.*//' < /etc/passwd
$ cut -d":" -f1 < /etc/passwd

If you need to use grep, and you have the GNU grep installed, you can use the following syntax.

$ grep -oE '^[^:]+' /etc/passwd

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }